Problem with operator precedence [duplicate]

谁都会走 提交于 2019-11-27 16:29:06

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

q = ++x || ++y && ++z

is grouped as

q = ((++x) || ((++y) && (++z)))

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 mere

q = (++x != 0)

The right-hand side of || operator is not even touched.

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 get x=2, y=1, z=1.

x=y=z=1;

Makes all the variables = 1

q=++x || ++y && ++z;

Since ++x makes it = 2 and since it is not zero it stops checking the other conditions because the first one is true.

Thus, x=2, and y and z = 1

kamilz

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;

q = ++x || ++y && ++z;

//ok, lets play by rule, lets see who takes who:
//first pass ++ is badass here (has highest precedence)
//q = (++x) || (++y) && (++z)

//second pass &&'s turn
//q = (++x) || ((++y) && (++z))

//done, let's do left to right evaluation
q = (++x) || rest..
q = (true)|| whatever..

hope that helps more clear.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!