Utkarsh Srivastav Utkarsh Srivastav - 2 months ago 17
C Question

Macro evaluation order


Possible Duplicate:

# and ## in macros




why the output of second printf is f(1,2) what is the order in which macro is evaluated?

#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;
}

output 12
f(1,2)

Answer

From http://gcc.gnu.org/onlinedocs/cpp/Argument-Prescan.html#Argument-Prescan

Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them.

Meaning:

  • f concatenates its argument and so its argument is not expanded
  • h does not stringify or concatenate its argument and so its argument is expanded.
  • g stringifies its argument, and so its argument is not expanded

h(f(1,2)) -> g(12) -> "12"

g(f(1,2)) -> "f(1,2)"