c - #define x 2|0 在 C 中

标签 c macros bitwise-operators bitwise-or

下面给出的代码是为了满足条件 (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 .

+ 绑定(bind)高于 == 绑定(bind)高于 |

预处理后,您的 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)

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

关于c - #define x 2|0 在 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43766599/

相关文章:

c - 宏将以前的宏标识符字符串化而不是替换它

c++ - 使用宏的错误转换

java - 如何在长的特定位置设置/取消设置?

调用 pthread_cond_broadcast 是否持有互斥量?

c++ - 将 JSON 日志记录宏转换为模板函数...代码中需要的参数名称

c - 是否可以将 char 指针分配给 float 值?

javascript - 为什么按位 "not 1"等于 -2?

java - 按位操作不与 Java 中的 print() 中的字符串连接

c - 斐波那契搜索

c# - 将 Lua 脚本加载到以文件名命名的表中