Search code examples
c++cmacrosscope

Scope of variable in a macro


In a file xyz.c

int p=2;  //global

#define sum(p,i) p+i

int main()
{
    printf("%d", sum(5,6));
}

output here would be 11 (and not 8); why?


Solution

  • Output is definitely 11.
    Because p is not considered as a variable inside the macro, it's just like a token which has a invocation value; e.g. (5,6). The scope of the token is limited to macro scope.

    Suppose you change the macro as below, then the output will be 8:

    #define sum(q,i) p+i
          //   ^^^ token 'q' is unused, so (5,6) is replaced with 'p+6'