What is the coolest form of swapping two variables in C?

I think this:

#define SWAP(x,y) x^=y^=x^=y

Lets check it out using this simple C code:

int main(int argc, char **argv) {
int x = 0x22, y = 0x33;
printf("%x,%x\n", x,y);
x^=y^=x^=y;
printf("%x,%x\n", x,y);
}

The output will be:

22,33
33,22

What happens:

x' = x ^ y
y' = y ^ x' = y ^ (x ^ y) = x
x" = x' ^ y' = (x ^ y) ^ x = y

We can check out the assembly dump too, just to verify the above statement:

8048419: 8b 44 24 18 mov 0x18(%esp),%eax
804841d: 31 44 24 1c xor %eax,0x1c(%esp)
8048421: 8b 44 24 1c mov 0x1c(%esp),%eax
8048425: 31 44 24 18 xor %eax,0x18(%esp)
8048429: 8b 44 24 18 mov 0x18(%esp),%eax
804842d: 31 44 24 1c xor %eax,0x1c(%esp)

Now lets check out the same in Java:

public class Xor {
public static void main(String[] args) {
int x = 0x33, y = 0x22;
System.out.printf("%x,%x\n",x,y);
x^=y^=x^=y;
System.out.printf("%x,%x\n",x,y);
}
}

The ouput:

33,22
0,33

Oops! Something went wrong! Lets check it: *$ javap -c Xor*

33: iload_1
34: iload_2
35: iload_1
36: iload_2
37: ixor
38: dup
39: istore_1
40: ixor
41: dup
42: istore_2
43: ixor
44: istore_1

Some explanation to the code above: iload_*n* loads the value of the *n*th variable and pushes it on the stack; isave_*n* removes the top value from the stack, and puts it into the *n*th variable; dup duplicates the top value on the stack; and ixor pops two values from the stack, performs a xor operation on them and pushes the result back to the stack.

So we can easily follow, what happened here:

x' = x ^ y // line 35-39
y' = y ^ x' = y ^ (x ^ y) = x // line 34,40-42
x" = x ^ y' = x ^ x = 0 // line 33,43-44

As you can see, when calculating x”, Java uses the original value of x, not the previously calculated one.

Conclusion: you have no fancy SWAP operation in java … đź™‚

### Like this:

Like Loading...

*Related*