[c++] How to use Macro argument as string literal?

I am trying to figure out how to write a macro that will pass both a string literal representation of a variable name along with the variable itself into a function.

For example given the following function.

void do_something(string name, int val)
{
   cout << name << ": " << val << endl;
}

I would want to write a macro so I can do this:

int my_val = 5;
CALL_DO_SOMETHING(my_val);

Which would print out: my_val: 5

I tried doing the following:

#define CALL_DO_SOMETHING(VAR) do_something("VAR", VAR);

However, as you might guess, the VAR inside the quotes doesn't get replaced, but is just passed as the string literal "VAR". So I would like to know if there is a way to have the macro argument get turned into a string literal itself.

This question is related to c++ c-preprocessor string-literals

The answer is


Perhaps you try this solution:

#define QUANTIDISCHI 6
#define QUDI(x) #x
#define QUdi(x) QUDI(x)
. . . 
. . .
unsigned char TheNumber[] = "QUANTIDISCHI = " QUdi(QUANTIDISCHI) "\n";

You want to use the stringizing operator:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}

#define NAME(x) printf("Hello " #x);
main(){
    NAME(Ian)
}
//will print: Hello Ian

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c-preprocessor

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’ Why does the C preprocessor interpret the word "linux" as the constant "1"? Preprocessor check if multiple defines are not defined How to use Macro argument as string literal? Define preprocessor macro through CMake? Why use #define instead of a variable How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor? C/C++ macro string concatenation Can gcc output C code after preprocessing? How to identify platform/compiler from preprocessor macros?

Examples related to string-literals

String in function parameter How can I get double quotes into a string literal? What is the backslash character (\\)? How to use Macro argument as string literal? What does the symbol \0 mean in a string-literal? Single quotes vs. double quotes in C or C++ python: SyntaxError: EOL while scanning string literal Difference between string object and string literal Windows path in Python C++ multiline string literal