Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macros evaluation in c programming language [duplicate]

Tags:

c

macros

Possible Duplicate:
What does “#define STR(a) #a” do?

#include <stdio.h>
  #define f(a,b) printf("yes")
  #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)));

  }

Can somebody explain why output is different for both printf() statements.

like image 647
Jagan Avatar asked Sep 23 '10 08:09

Jagan


1 Answers

The output is different because of the order in which the preprocessor does things, which is described in section 6.10.3 (and those following) in the C99 standard. In particular, this sentence from 6.10.3.1/1:

A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token, is replaced by the corresponding argument after all macros contained therein have been expanded.

So in the first line, when expanding the invocation of h, the argument f(1,2) is expanded before it replaces h's parameter a. The # only comes into play later when the resulting invocation of g is seen when the output of all that is rescanned.

But on the second line, the # is seen immediately and the "unless preceded by..." clause of the quotation above triggers the different behaviour.

See also the relevant C-FAQ entry.

like image 98
John Marshall Avatar answered Nov 18 '22 13:11

John Marshall