C 中逻辑运算符的优先级
如果你查看 C 的优先级表,你会看到 &&优先级高于||。
但是看一下下面的代码:
a=b=c=1;
++a || ++b && ++c;
printf("%d %d %d\n",a,b,c);
它打印出“2 1 1”,这意味着“++a”首先被计算,一旦程序在那里看到一个 TRUE,它就在那里停止,因为另一边是什么|| 的并不重要。
但自从&&优先级高于 ||,难道不应该先评估“++b && ++c”,然后将结果插回“++a || result”吗? (在这种情况下,程序将打印“1 2 2”)。
Possible Duplicate:
why “++x || ++y && ++z” calculate “++x” firstly ? however,Operator “&&” is higher than “||”
If you look at C's precedence table, you'll see that && has higher precedence than ||.
But take a look at the following code:
a=b=c=1;
++a || ++b && ++c;
printf("%d %d %d\n",a,b,c);
It prints out "2 1 1", meaning that the "++a" is evaluated first, and once the program sees a TRUE there it stops right there, because what is on the other side of the || is not important.
But since && has higher precedence than ||, shouldn't "++b && ++c" be evaluated first, and then the result plugged back into "++a || result" ? (in this case the program would print "1 2 2").
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试着用括号想象一下:
equals
是从左到右计算的。
如果&&和 ||将具有相同的优先级,看起来像
Just try to imagine it with parentheses:
equals
which is evaluated from left to right.
if && and || would have the same precedence, it would look like
优先级规则仅规定它将像这样进行评估:
现在出现了逻辑运算符的短路行为,这表明您必须从左到右评估项,并在知道结果时停止。右边的部分永远不会被执行。
The precedence rules only say that it will be evaluated like this:
Now comes the short circuiting behavior of the logic operators which says that you have to evaluate terms from left to right and stop when the result is known. The part on the right never gets executed.
优先级和求值顺序是完全不同的两件事。对于逻辑运算符表达式,求值始终是从左到右。表达式
++a || ++b && ++c
被解释为表达式解析为
++a || (++b && ++c)
;如果子表达式++a
或++b && 中的一个为真,则整个表达式为真。 ++c
是正确的。Precedence and order of evaluation are two completely different things. For logical operator expressions, evaluation is always left-to-right. The expression
++a || ++b && ++c
is interpreted asThe expression is parsed as
++a || (++b && ++c)
; the whole expression is true if either of the subexpressions++a
or++b && ++c
is true.<代码>&&仅在解析树中具有更高的优先级。但编译器将代码优化为
&& has higher precedence
only in parse tree. But compiler optimizes the code as您的示例
++a || ++b && ++c
与++a || 相同(++b && ++c)
。Your example
++a || ++b && ++c
is the same as++a || (++b && ++c)
.