简体   繁体   中英

Macro inside Macro

Consider the following code:

#define P1(x) x+x
#define P2(x) 2*P1(x)

int main()
{
    int a = P1(1) ? 1 : 0;
    int b = P2(a)&a;

    return 0;
}

Now, I thought that the compiler first replacing the macros with their values and so int b = 2*a+a&a; (and since a=1 then b=3 ). Why isn't it so?

There's no precedence in your operation (it is just a textual substitution) thus, as you've noted,

#define P1(x) x+x
#define P2(x) 2*P1(x)

int a = P1(1) ? 1 : 0; // 1

and since & has lower precedence than + , it is equivalent to

int b = ((2 * a) + a) & a;

ie only the rightmost bit is set on b .

((2 * a) + a)  011 &
      a        001 =
--------------------
      b        001

This is because & has lower precedence than that of addition + operator. The grouping of operands will take place as

int b = ( (2*a + a) & a ); 

Therefore, (2*a + a) = 3 and 3 & 1 = 1 ( 011 & 001 = 001 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM