#define x 2|0 在 C 中

#define x 2|0 in C

编写下面给出的代码以满足条件 (x == x+2) 在 C 中返回 true。

#include<stdio.h>
#define x 2|0

int main()  
{
    printf("%d",x==x+2); 
    return 0;
}

在上面的代码中为什么 printf() 正在打印 2 (如果我写 x+3 我得到 3 等等)。

谁能解释一下给定的宏是如何工作的。

C中的|运算符有什么用,宏

有什么用
#define x 2|0

是什么意思?我在其他问题中读到了宏,但没有问题解释过类似的例子。

TL;DR; 阅读 operator precedence

+== 更高,后者比 |.

更高

经过预处理后,您的 printf() 语句看起来像

 printf("%d",2|0==2|0+2);

相同
 printf("%d",2|(0==2)|(0+2));

这是

printf("%d",2|0|2);

忠告:不要在实际场景中编写此类代码。启用最低级别的编译器警告后,您的代码会生成

source_file.c: In function ‘main’:
source_file.c:4:12: warning: suggest parentheses around comparison in operand of ‘|’ [-Wparentheses]
 #define x 2|0
            ^
source_file.c:8:21: note: in expansion of macro ‘x’
     printf("%d\n\n",x==x+2); 
                     ^
source_file.c:4:12: warning: suggest parentheses around arithmetic in operand of ‘|’ [-Wparentheses]
 #define x 2|0
            ^
source_file.c:8:24: note: in expansion of macro ‘x’
     printf("%d\n\n",x==x+2);

因此,当您将 MACRO 定义更改为 理智 时,例如

#define x (2|0)

结果也会改变,因为显式优先级 then 将由括号保证。

在 运行 预处理器之后,gcc -E main.c 你会得到:

int main()
{
    printf("%d",2|0==2|0 +2);
    return 0;
}

由于 (0==2) 为 0,2|0|2