Possible Duplicate:
What does “#define STR(a) #a” do?
#include <stdio.h>
#define f(a,b) printf("yes")
#define g(a) #a
#define h(a) g(a)
int main()
{
printf("%s\n",h(f(1,2)));
printf("%s\n",g(f(1,2)));
}
Can somebody explain why output is different for both printf() statements.
The output is different because of the order in which the preprocessor does things, which is described in section 6.10.3 (and those following) in the C99 standard. In particular, this sentence from 6.10.3.1/1:
A parameter in the replacement list, unless preceded by a #
or ##
preprocessing token or followed by a ##
preprocessing token, is replaced by the corresponding argument after all macros contained therein have been expanded.
So in the first line, when expanding the invocation of h
, the argument f(1,2)
is expanded before it replaces h
's parameter a
. The #
only comes into play later when the resulting invocation of g
is seen when the output of all that is rescanned.
But on the second line, the #
is seen immediately and the "unless preceded by..." clause of the quotation above triggers the different behaviour.
See also the relevant C-FAQ entry.
After the preprocessor is done with the macro expansion, the compiler sees this:
int main()
{
printf("%s\n","printf(\"yes\")");
printf("%s\n","f(1,2)");
}
This is a common technique to layer in an "extra" indirection to control when you get stringification and when you get actual macro evaluation.
Basically, macro evaluation happens from the "outside in", not the other way around. The wikipedia page says "parameters are not parsed for macro replacement first" which I believe is refering to the same thing.