Problem with operator precedence [duplicate]

a 夏天 提交于 2019-12-17 14:57:05

问题


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);
}

回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/7212482/problem-with-operator-precedence

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