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.
There is no way to convert a macro argument into a character constant. If you want to stringify the result of expansion of a macro argument, you have to use two levels of macros. s is stringified when it is used in str, so it is not macro-expanded first.
To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.
The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.
The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.
Use the preprocessor #
operator:
#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With