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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With