简体   繁体   English

宏内宏

[英]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; 现在,我认为编译器首先将宏替换为其值,因此int b = 2*a+a&a; (and since a=1 then b=3 ). (并且由于a=1b=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 . 即在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 ). 因此, (2*a + a) = 33 & 1 = 1011 & 001 = 001 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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