The rules in C # are extremely simple. It:
- expression sub-expressions are evaluated LEFT TO RIGHT, period, end of story.
- A side effect of the increment operator occurs when the operator is evaluated.
So, in your case, it breaks like that; I will pretend that we do this in C instead of C #, so where addresses and markup are more understandable.
x = y++ + x++;
Rate the address x and save it.
t1 = &x;
Rate the address y.
t2 = &y;
Calculate the value stored in the address just calculated. This is 35.
t3 = *t2; // 35
The calculated value is the value of the expression; this is the value before the increment.
Add one to this value.
t4 = t3 + 1; // 36
Store 36 in the address. y is now 36.
*t2 = t4;
Now do the same for x ++:
t5 = &x; t6 = *t5; // 20 t7 = t6 + 1; // 21 *t5 = t7; // x = 21
OK, now we have to make an addition:
t8 = t3 + t6; // 35 + 20 = 55
and assign this to the address computed first:
*t1 = t8;
At the end of this statement, x has three meanings. 20, 21 and 55. y has two meanings: 35 and 36. x is now 55, and y is now 36.
y = ++y + ++x;
Now we do the same thing again, except that we use values ββafter increments. Follow on:
t1 = &y; t2 = &y; t3 = *t2; // 36 t4 = t3 + 1; // 37 *t2 = t4; // y = 37; t5 = &x; t6 = *t5; // 55 t7 = t6 + 1; // 56; *t5 = t7; // x = 56; t8 = t4 + t7; // 93 *t1 = t8; // y = 93;
So, by the end of this expression, y has three meanings: 36, 37, and 93. x has two meanings: 55 and 56. y is now 93, and x is now 56.
I expected the output to be x = 57 and y = 94.
Why did you expect this? Your expectation ran counter to the C # specification; I would be interested to know why you were expecting the wrong result. How did you expect the code to be generated for this? Did you expect the attack to happen? Why would they do that? The increment occurs when the value of the increment operator is calculated and, obviously, should happen before the addition, which, obviously, should happen before the destination. Therefore, increment cannot occur after assignment.
For some reason, the post increment statement does not start on line 3.
How did you come to this conclusion? I assure you that this is certainly being done. Upon completion of the debugger, if you do not believe me.