-3

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?

klimenkov
  • 347
  • 2
  • 8

3 Answers3

7

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.

RamanSB
  • 1,162
  • 9
  • 26
  • Operators priority says that we must always start with increment and only then do addition. It does not depend on order from left to right. – klimenkov Sep 03 '15 at 23:03
  • Why i compiled the example in C and the result was `21,21` ? – Jean Jung Sep 03 '15 at 23:06
  • @klimenkov you are mistaking order of evaluation and precedence – RamanSB Sep 03 '15 at 23:10
  • @JeanJung C does not declare rules how to evaluate expressions. But Java and C# do. – klimenkov Sep 03 '15 at 23:11
  • @klimenkov oh, sorry, my mistake. That's true. When i have read the question was clearly true that the behavior is because the operands analyze orders, i posted an answer and then i deleted it when i have seen the C results. I have forgot that C does not implies rules of precedence. – Jean Jung Sep 03 '15 at 23:35
0

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 ++.

SimpleVar
  • 14,044
  • 4
  • 38
  • 60
0

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.

ashavitt
  • 141
  • 1
  • 1
  • 5