Swapping 2 variables without introducing a third one can be useful when the efficiency is critical that you want everything stay in registers. There are a few ways to do this.
1 2 3 4 5 6 7 8 |
int a, b; // Swapping a and b a = a + b; b = a - b; a = a - b; // a, b is swapped |
Notice that this method still works even when a overflows during the first addition. Try it to see what I mean.
You can also do this using XOR operator like so.
1 2 3 4 5 6 7 8 |
int a, b; // Swapping a and b a = a ^ b; b = a ^ b; a = a ^ b; // a, b is swapped |
Would also like to mention the right way to do it in Python for readability. No one cares about performance when they are writing in Python right?
1 |
a, b = b, a |