Warm tip: This article is reproduced from serverfault.com, please click
c

c-为什么&运算符仅在变量中起作用而不在内联语句中起作用

(c - Why does the & operator only work in variables and not in inline statements)

发布于 2020-11-27 23:41:25
printf("%i\n",2&2==2);

这应该打印出1,但我得到0,这为什么呢?

int ans=2&2;
printf("%i\n",ans==2);

此打印1,为什么第一种方式不起作用?if语句也是如此

Questioner
BackSpace7777777
Viewed
0
Bill Lynch 2020-11-28 08:35:05

操作顺序与你认为的不同。在一行中编写它的正确方法是:

printf("%i\n", (2 & 2) == 2); // Prints 1