gpt4 book ai didi

c - #define x 2|0 在 C 中

转载 作者:太空宇宙 更新时间:2023-11-04 06:16:47 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com