Reputation: 33
What the difference of two define
?
#define NUM 123
#define NUM_TO_STRING1(x) #x
#define NUM_TO_STRING(x) NUM_TO_STRING1(x)
printf("NUM_TO_STRING1: %s\n", NUM_TO_STRING1(NUM));
printf("NUM_TO_STRING: %s\n", NUM_TO_STRING(NUM));
result:
NUM_TO_STRING1: NUM
NUM_TO_STRING: 123
Why NUM_TO_STRIN1
can not change the NUM
to string 123
?
Upvotes: 3
Views: 139
Reputation: 166
In your case:
NUM_TO_STRING1(NUM) becomes NUM
With #, NUM is stringified. Does not be replaced with 123.
NUM_TO_STRING(NUM) becomes NUM_TO_STRING1(123)
123 is stringified, and the result is 123
Upvotes: 1
Reputation: 6116
See this link:
At the end it says:
If you want to stringify the result of expansion of a macro argument, you have to use two levels of macros.
#define xstr(s) str(s)
#define str(s) #s
#define foo 4
str (foo)
==> "foo"
xstr (foo)
==> xstr (4)
==> str (4)
==> "4"
and read here about order of Argument scanning in macros:
Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them.
Upvotes: 2
Reputation: 234885
With the #
, you're asking it not to. All #
does is to stringify the thing that immediately follows it. The idiom that I think you're trying to exploit is a common one:
#define STR(_a) #_a
#define XSTR(_a) STR(_a)
#define BAR foo
With things set up like this,
STR(BAR)
Will give you "BAR"
and
XSTR(BAR)
Will give you "foo"
Upvotes: 3