1,184 views
5 votes
5 votes
#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; 
}

Just by looking at the program one "might" expect the output to be, the same for both the printf statements. But on running the program you get it as:

bash$ ./a.out
12
f(1,2)
bash$



Why is it so?

1 Answer

Best answer
2 votes
2 votes

https://stackoverflow.com/questions/8062271/why-i-am-not-getting-the-expected-output-in-the-following-c-programme

In the second definition, #a means to print the macro argument as a string. This will turn, e.g. g(f(a,b)) into "f(a,b)", but it won't do macro-expansion on its arguments.

The third definition doesn't add anything to the second, but by passing its argument to another macro, it forces full macro expansion of its argument. So, h(a) creates a string of 'a' with all macros fully expanded.

#define xstr(s) str(s)
#define str(s) #s
#define foo 4
str (foo)
     → "foo"
xstr (foo)
     → xstr (4)
     → str (4)
     → "4"

Above example taken from https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html#Stringizing

selected by

Related questions

1 votes
1 votes
2 answers
1
AskHerOut asked Oct 24, 2017
487 views
Can you see why the output of the following code is 256?main () { int a=0x1ff; char *careful= &a; *careful = 0; printf("%d", a); }