Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro evaluation order [duplicate]

Tags:

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) 
like image 899
Utkarsh Srivastav Avatar asked Jan 06 '12 07:01

Utkarsh Srivastav


1 Answers

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)"

like image 195
Pubby Avatar answered Sep 20 '22 17:09

Pubby