C 中的运算符优先级
下面的程序似乎没有按预期工作。 '&&'的优先级高于“||”,因此实际输出令人困惑。谁能解释一下o/p吗?
#include <stdio.h>
int main(int argc, char *argv[])
{
int x;
int y;
int z;
x = y = z = 1;
x++ || ++y && z++;
printf("%d %d %d\n", x, y, z);
return 0;
}
实际输出为:2 1 1
TIA。
Possible Duplicate:
why "++x || ++y && ++z" calculate "++x" firstly ? however,Operator "&&" is higher than "||"
The following program does not seem to work as expected. '&&' is to have higher precendence than '||', so the actual output is confusing. Can anyone explain the o/p please?
#include <stdio.h>
int main(int argc, char *argv[])
{
int x;
int y;
int z;
x = y = z = 1;
x++ || ++y && z++;
printf("%d %d %d\n", x, y, z);
return 0;
}
The actual output is: 2 1 1
TIA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
优先级和求值顺序没有任何关系。
&&
的优先级高于||
意味着表达式被解释为因此,
||
的左侧操作数是首先计算(必需的,因为它后面有一个序列点),并且由于它计算非零,所以右侧操作数(++y && z++)
是从未评价过。Precedence and order of evaluation have no relation whatsoever.
&&
having higher precedence than||
means simply that the expression is interpreted asThus, the left-hand operand of
||
is evaluated first (required because there is a sequence point after it), and since it evaluates nonzero, the right-hand operand(++y && z++)
is never evaluated.令人困惑的行被解析为:
然后从左到右计算。由于
||
是一个短路求值器,一旦它计算左侧,它就知道整个表达式将求值为真值,因此它会停止。因此,x
会递增,而y
和z
不会受到影响。The confusing line is parsed as if it were:
Then this is evaluated left-to-right. Since
||
is a short-circuit evaluator, once it evaluates the left side, it knows that the entire expression will evaluate to a true value, so it stops. Thus,x
gets incremented andy
andz
are not touched.运算符优先级规则意味着表达式被视为如同编写的那样:
由于
x++
为 true,因此根本不会计算||
表达式的 RHS - 因此结果你看。The operator precedence rules mean the expression is treated as if it were written:
Since
x++
is true, the RHS of the||
expression is not evaluated at all - hence the result you see.