0

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

意思是?我在其他问题中阅读了有关宏的信息,但没有问题解释了类似的示例。

4

2 回答 2

3

TL;博士; 阅读运算符优先级

+绑定高于==哪个绑定高于|

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

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

于 2017-05-03T17:42:32.133 回答
1

运行预处理器后,gcc -E main.c您将获得:

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

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

于 2017-05-03T17:42:40.773 回答