How to use Macro argument as string literal?

C++C PreprocessorString Literals

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

Use the preprocessor # operator:

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

Solution 2 - C++

You want to use the stringizing operator:

#define STRING(s) #s

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

Solution 3 - C++

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

Solution 4 - C++

Perhaps you try this solution:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIanView Question on Stackoverflow
Solution 1 - C++MorwennView Answer on Stackoverflow
Solution 2 - C++chrisView Answer on Stackoverflow
Solution 3 - C++Mikele ShtembariView Answer on Stackoverflow
Solution 4 - C++ZiliView Answer on Stackoverflow