Reputation: 3915
Why in one case nested macros works while in the other does not?
Case 1:
#define name(val) #val
#define name2(front, back) name(front ## back)
...
printf("%s\n", name2(foo, bar)); // foobar
Case 2:
#define paste(front, back) front ## back
#define name(val) #val
#define name2(front, back) name(paste(front, back))
...
printf("%s\n", name2(foo, bar)); // paste(foo, bar)
Upvotes: 6
Views: 11799
Reputation: 58507
Because the arguments to a macro aren't expanded if they appear along with a #
or ##
in the macro body (as is the case with val
in name
). See the accepted answer for this question.
So in your second case you'll need to add an intermediate step to ensure that the argument is expanded. E.g. something like:
#define paste(front, back) front ## back
#define name(val) #val
#define expand(val) name(val) // expand val before stringifying it
#define name2(front, back) expand(paste(front, back))
Upvotes: 6