This question already has answers here:
Closed 8 years ago.
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
printf("%d\n",f(1,2));
which, in turn, results into
printf("%d\n",12);
(called with gcc -E
).
Your two lines result into
printf("%s\n","12");
printf("%s\n","f(1,2)");
What happens here?
f(1,2)
is clear - 1
and 2
just get sticked together.
g(something)
just reproduces something
as a string, without treating it specially -> "f(1,2)"
.
h(something)
, in turn, lets the result of g(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 in h(YOUR_MACRO)
case - h() does stringification indirectly and so it complies with C macro arguments expansion rules and is expanded further.
First one:
printf("%s\n",h(f(1,2)));
becomes:
g(12)
which in turn becomes
"12"
Second one:
printf("%s\n",g(f(1,2)));
becomes
"f(1,2)"
since #
converts the argument to a string parameter.