2 ms·
You'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
by dragontamer 4y ago
You'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.