cc-preprocessorstringification

# and ## in macros


  #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?


Solution

  • Because that is how the preprocessor works.

    A single '#' will create a string from the given argument, regardless of what that argument contains, while the double '##' will create a new token by concatenating the arguments.

    Try looking at the preprocessed output (for instance with gcc -E) if you want to understand better how the macros are evaluated.