Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why i am not getting the expected output in the following c programme? [duplicate]

Tags:

c

macros

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?

like image 589
bornfree Avatar asked Nov 09 '11 08:11

bornfree


1 Answers

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.

like image 111
glglgl Avatar answered Nov 15 '22 19:11

glglgl