For the unfamiliar, what does this pattern do exactly?
cat > a.c
#define X(s) #s
#define S(s) X(s)
char *f(void) return { S(A); }
^D
cc -E a.c
char *f(void) return { "A"; }
cc -DA=B -E a.c
char *f(void) return { "B"; }
More interestingly, you can use this trick to create code where some user-specified word appears as a string and as the name of the function. Exercice: write a macro M(x) such that compiling the code M(foo)
M(bar)
results in void print_foo(void) { puts("foo"); }
voir print_bar(void) { puts("bar"); }Ah, the poor man's introspection and reflection with C macros.
shudder
#define F 42
#define X(s) #s
X(5) // Expands to "5" (as a string literal)
X(F) // Expands to "F" not "42"
If you add one level of recursive macro expansion, though, that expands the macro argument as well as the macro definition: #define F 42
#define X(s) #s
#define S(s) X(s)
S(5) // "5" as expected
S(F) // "42" because S(F) expands to X(42) expands to "42"