3 ms·
>Warning: if x == y, then instead of swapping, the two values are set to zero. Huh, what?
by garaetjjte 4y ago
>Warning: if x == y, then instead of swapping, the two values are set to zero.
Huh, what?
- dragontamer 4y agoYou're right. Sorry, my bad. I misremembered the actual issue. The issue is: void xor_swap(int& x, int& y){ x ^= y; y ^= x; x ^= y; } The issue is *aliasing*. If the pointer &x == &y, then everything goes to crap. When the pointers alias to themselves, the function degenerates into: x ^= x; x ^= x; x ^= x; Which sets x (and the y value) to zero. In contrast: void regular_swap(int& x, int& y){ int tmp = x; x = y; y = tmp; } This always works, even with aliasing.