Thursday, June 12, 2008

C# Puzzle No.2 (level: intermediate)

Following code snippet is commonly used in C/C++ to exchange values of two integer values with no help of any additional variable.

int x, y;
 
x ^= y ^= x ^= y;

This surprisingly does not work in C#. Can you explain why?

2 comments:

apl said...

Before the expression is evaluated, argument values are pushed onto the stack, therefore assignments are only updating the variables, but not the expression arguments. The expression is carried out as follows:

1. Push x, y, x and y onto the stack. The stack is:

y0
x0
y0
x0

x is x0.
y is y0.

2. XOR the top two values and store them in x. The stack is:

x0 ^ y0
y0
x0

x is x0 ^ y0.
y is y0.

3. XOR the top two values and store them in y. The stack is:

x0 ^ y0 ^ y0 = x0
x0

x is x0 ^ y0
y is x0

4. XOR the top two values and store them in x. The stack is:

x0 ^ x0 = 0

x is 0
y is x0

a said...

beautiful