Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this C code work?

What is a##b & #a?

  #define f(a,b) a##b
  #define g(a)   #a
  #define h(a) g(a)

  main()
  {
          printf("%s\n",h(f(1,2)));  //how should I interpret this?? [line 1]
          printf("%s\n",g(f(1,2)));  //and this? [line 2]
  }

How does this program work?


The output is

12
f(1, 2)

now I understand how a##b & #a work. But why is the result different in the two cases (line 1 and line 2)?

like image 221
Moeb Avatar asked Nov 06 '09 09:11

Moeb


2 Answers

The ## concatenates two tokens together. It can only be used in the preprocessor.

f(1,2) becomes 1 ## 2 becomes 12.

The # operator by itself stringifies tokens: #a becomes "a". Therefore, g(f(1,2)) becomes "f(1,2)" when the preprocessor is done with it.

h(f(1,2)) is effectively #(1 ## 2) which becomes #12 which becomes "12" as the preprocessor runs over it.

like image 55
Wernsey Avatar answered Sep 18 '22 17:09

Wernsey


For questions like these (and also more "real-world" problems having to do with the preprocessor), I find it very helpful to actually read the code, after it has been preprocessed.

How to do this varies with the compiler, but with gcc, you would use this:

$ gcc -E test.c

(snip)
main()
{
        printf("%s\n","12");
        printf("%s\n","f(1,2)");
}

So, you can see that the symbols have been both concatenated, and turned into a string.

like image 30
unwind Avatar answered Sep 19 '22 17:09

unwind