运算符优先级问题
O/p 结果为 x=2,y=1,z=1,这与运算符优先级不一致。我在 Turbo C++ 编译器上运行这个:
void main()
{
int x,y,z,q;
x=y=z=1;
q=++x || ++y && ++z;
printf("x=%d y=%d z=%d",x,y,z);
}
The O/p comes out to be x=2,y=1,z=1 which doesnt agree with the operator precedence. I was running this on Turbo c++ compiler:
void main()
{
int x,y,z,q;
x=y=z=1;
q=++x || ++y && ++z;
printf("x=%d y=%d z=%d",x,y,z);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实际上结果完全符合标准 C。逻辑或运算符 (
||
) 在++x
之后短路,因为它的计算结果为非零数,因此其余的都被忽略。所以从
x=1
、y=1
、z=1
开始,短路后,你得到x=2< /code>、
y=1
、z=1
。Actually the result is in complete accordance with standard C. The logical or operator (
||
) short circuits after++x
because it evaluates to a non-zero number, so the rest of them are ignored.So starting at
x=1
,y=1
,z=1
, after the short circuit, you getx=2
,y=1
,z=1
.运算符优先级无论如何都不会决定运算符的执行顺序。运算符优先级仅定义运算符及其操作数之间的分组。在您的情况下,运算符优先级表示表达式
被分组为
其余部分与运算符优先级完全无关。
其余的由每个特定运算符的语义决定。本例中的顶级运算符是
||
。||
运算符的特定属性是它始终首先计算其左侧。如果左侧尺寸结果非零,那么它甚至不会尝试评估右侧。这正是您的情况所发生的情况。左侧是
++x
,其计算结果为非零值。这意味着具有给定初始值的整个表达式在功能上等同于仅仅||
运算符的右侧甚至没有被触及。Operator precedence does not in any way determine the order in which the operators are executed. Operator precedence only defines the grouping between operators and their operands. In your case, operator precedence says that the expression
is grouped as
The rest has absolutely nothing to do with operator precedence at all.
The rest is determined by the semantics of each specific operator. The top-level operator in this case is
||
. The specific property of||
operator is that it always evaluates its left-hand side first. And if the left-hand size turns out to be non-zero, then it does not even attempt to evaluate the right-hand side.This is exactly what happens in your case. The left-hand side is
++x
and it evaluates to a non-zero value. This means that your whole expression with the given initial values is functionally equivalent to a mereThe right-hand side of
||
operator is not even touched.使所有变量 = 1
由于
++x
使其 = 2,并且由于它不为零,因此它停止检查其他条件,因为第一个条件为true
。因此,
x=2
,并且y 和 z = 1
Makes all the variables = 1
Since
++x
makes it = 2 and since it is not zero it stops checking the other conditions because the first one istrue
.Thus,
x=2
, andy and z = 1
逻辑
&&
(AND
) 和||
(OR
) 运算符会发生短路。“逻辑运算符保证从左到右评估其操作数。但是,它们评估确定表达式结果所需的最少数量的操作数。这称为“短路”评估。”
因此,对于逻辑运算符,始终按从左到右的顺序计算(无论
||
或&&
)。正如前面提到的,这里的优先级仅决定谁抢谁。
然后从左到右规则;
希望能帮助更清楚。
Logical
&&
(AND
) and||
(OR
) operators are subject to Short-Circuit."Logical operators guarantee evaluation of their operands from left to right. However, they evaluate the smallest number of operands needed to determine the result of the expression. This is called "short-circuit" evaluation."
Thus, for logical operators always evaluated as (no matter
||
or&&
) left to right.And as previously mentioned, precedence here only determines who takes who.
Then left to right rule;
hope that helps more clear.