Possible Duplicate:
What does “#define STR(a) #a” do?
Macros evaluation in c programming language
#include <stdio.h>
#define f(a,b) a##b
#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)));
return 0;
}
I was expecting the output to be same for both the printf. But what I am getting is different(given below)
12
f(1,2)
can someone explain what is the reason and why is it happening in detail?
I extended your program with an additional line
which, in turn, results into
(called with
gcc -E
).Your two lines result into
What happens here?
f(1,2)
is clear -1
and2
just get sticked together.g(something)
just reproducessomething
as a string, without treating it specially ->"f(1,2)"
.h(something)
, in turn, lets the result ofg(something)
expand.C standard states that macro arguments aren't expanded if they are stringified or concatenated. That is why
g(YOUR_MACRO)
YOUR_MACRO isn't expanded. However inh(YOUR_MACRO)
case - h() does stringification indirectly and so it complies with C macro arguments expansion rules and is expanded further.First one:
becomes:
which in turn becomes
Second one:
becomes
since
#
converts the argument to a string parameter.