Wednesday, February 6, 2013

code sample question 1

int x = 10;  x += x--;  value of x?



x += x--;

This is equivalent to:
x = x + x--;

Which is equivalent to:

int a1 = x; // a1 = 10, x = 10
int a2 = x--; // a2 = 10, x = 9
x = a1 + a2; // x = 20

So x is 20 afterwards - and that's guaranteed by the spec.



  • 1) subexpressions are always evaluated left to right. Period. Evaluation of a subexpression may induce a side effect.


2) execution of operators is always done in the order indicated by parentheses, precedence and associativity. Execution of operators may induce a side effect.

The "x" to the left of the += is the leftmost subexpression, and therefore rule (1) applies. Its value is computed first -- 10.

The x-- to the right of the += is the next one in left-to-right order, so it is evaluated next. The value of x-- is 10, and the side effect is that x becomes 9. This is as it should be, because -- is of higher precedence than +=, so its side effect runs first.

Finally, the side effect of += runs last. The two operands were 10 and 10, so the result is to assign 20 to x.

I get questions about this all the time. Remember, the rules are very straightforward: subexpressions left-to-right, operators in precedence order, period.



  • a difference between --x and x-- here. 

If you had written x += --x;
this would be equivalent to x = x + --x;
then you would get 19.
This is because the value of x is decremented and the resulting value is used in the expression
(unlike x-- where the original value of x is used in the expression).

This expression x = x + --x + x will give 28 because the third timefourth time (see comments) x is evaluated it is 9.



http://stackoverflow.com/questions/2299437/int-x-10-x-x-in-net-why

No comments:

Post a Comment