5

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)
Cœur
  • 37,241
  • 25
  • 195
  • 267
Georgii Oleinikov
  • 3,865
  • 3
  • 27
  • 27
  • 1
    Did you look inside the preprocessed form, e.g. as obtained by `gcc -C -E` on Linux, of your source program (to which you could add "intermediate" code like `printf("%s\n", name(goo))`? – Basile Starynkevitch Mar 17 '13 at 07:54
  • 2
    This link is helpful for me when learning http://gcc.gnu.org/onlinedocs/cpp/Macros.html#Macros – yuan Mar 17 '13 at 11:11

1 Answers1

5

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))
Community
  • 1
  • 1
Michael
  • 57,169
  • 9
  • 80
  • 125