简体   繁体   中英

Possible incorrect operators priority

Consider the following pseudo-code:

int x = 10;
int y = 10;

x = x + x++;
y = y++ + y;

print(x); // 20
print(y); // 21

C-like programming languages like C# or Java say that increment has higher precedence, than + operator. So it should be 21 in both cases.

Why does it print two different results?

Remember we work from left to right.

Let's deal with x first then y.

x

x = x + x++;

We are going from left to right...

x = 10 + (10++)

Note: As we go from left to right the post increment operator on x on the far right has no effect on the x which appears first on the RHS.

x = 20

y

y = y++ + y;

y = 10++ + 11;

Again we go from left to right, the increment operator post increments y from 10 to 11, hence the y on the far right becomes 11, thus yielding (10 + 11) = 21.

I believe the + operator has higher precedence than ++ , so the + operator is evaluated first, but in order to evaluate it - it must evaluate the left and right operators of it.

In the second example the left operator is evaluated first so y increments before the right hand is evaluated.


In the Precedence and Order of Evaluation documentation, you can see that + is above += which is basically what ++ is. Above the + is the prefix ++ which is not to be confused with the postfix ++ .

When y++ + y is evaluated, y++ is evaluated before y . So the left hand side is evaluated to 10, and the right hand side will be evaluated to 11 due to the previous incrementation. When x + x++ is evaluated, x is evaluated before x++ . So both sides will be evaluated to 10, then x will be evaluated to 11 just before the = operand will evaluate x to 20.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM