【问题标题】:#define x 2|0 in C#define x 2|0 在 C 中
【发布时间】:2017-05-03 17:32:54
【问题描述】:

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

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

【问题讨论】:

  • 预处理后的代码是什么意思?
  • 展开宏。查看运算符优先级表。理解。开悟吧。
  • 我知道你在学习。学习这些东西很好……但以后不要真正使用它。
  • @VoidLimbo 晦涩难懂的代码只适用于 c00L h4xx0r 比赛。
  • #define x 1.0e100 也可能满足x==x+2

标签: c macros bitwise-operators bitwise-or


【解决方案1】:

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)

结果也会发生变化,因为括号中的显式优先级将得到保证。

【讨论】:

  • 谢谢@Sourav 我现在明白了。
  • 我也会记住您的建议。我不经常使用宏,我只是想知道它是如何工作的。现在我对宏有了更多的了解。谢谢你@Sourav
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 2022-11-24
    • 1970-01-01
    • 2021-05-18
    相关资源
    最近更新 更多