C Integer swap
8
Nifty way to swap two integers in C (C++) without using a temporary variable. Uses one line of code (3 assignments).
int x = 3;
int y = 5;
printf("Before\n[x, y] = [%d, %d]\n", x, y);
x ^= y ^= x ^= y;
printf("After\n[x, y] = [%d, %d]\n", x, y);
Output::
Before
[x,y] = [3,5]
After
[x,y] = [5, 3]






As far as the XOR swap being less readable, I respectfully disagree. Given that GCC will produce the same output regardless, I almost always use the XOR algo, simply because temporary variables are needless cruft in my beautiful code! *grin*
I've got good news, and I've got bad news:
The universe is merely a figment of my imagination.
Now are you ready for the bad news?
Still neat, though.
Keep this one in mind for hardware programming with a latch or flip-flop.