How do you swap the values of 2 int variables without using a third variable?
Extra points if it’s a bit obscure…
Now don’t cheat and look at the comments, once you got it post it as a comment.
How do you swap the values of 2 int variables without using a third variable?
Extra points if it’s a bit obscure…
Now don’t cheat and look at the comments, once you got it post it as a comment.
x = x + y;
y = x – y;
x = x – y;
…?
Yea.. but there’s another way… (I think.. needs testing)
int x = 7; int y = 56;
x = (y = (x = y ^ x ) ^ y) ^ x;
😛
In python (and I believe in Ruby) you can just do this:
a = 1
b = 2
print a, b
a,b = b,a
print a, b
Why I like python ;P
I suppose that’s a good reason to learn other languages :P.
Just for the sake of being pedantic completeness, I decided to disassemble the source code to see what the compiler was doing:
6 6 LOAD_CONST 2 (2)
9 STORE_FAST 1 (b)
7 12 LOAD_FAST 0 (a)
15 PRINT_ITEM
16 LOAD_FAST 1 (b)
19 PRINT_ITEM
20 PRINT_NEWLINE
8 21 LOAD_FAST 1 (b)
24 LOAD_FAST 0 (a)
27 ROT_TWO
28 STORE_FAST 0 (a)
31 STORE_FAST 1 (b)
9 34 LOAD_FAST 0 (a)
37 PRINT_ITEM
38 LOAD_FAST 1 (b)
41 PRINT_ITEM
42 PRINT_NEWLINE
43 LOAD_CONST 0 (None)
46 RETURN_VALUE
The op code in question seems to be ROT_TWO and the definition for that is ‘Swaps the two top-most stack items’. I guess the next question is what python’s definition of swaps is :P.