Hacker News new | ask | show | jobs
by patcdr 6194 days ago
It still works fine if a and b are the same value.

Here's the general proof:

a ^= b (a = a ^ b, b = b)

b ^= a (a = a ^ b, b = b ^ (a ^ b) = a)

a ^= b (a = b ^ (a ^ b) = b ,b = a)

Now, let's replace all references initial values with constant c:

a ^= b (a = c ^ c = 0, b = c)

b ^= a (a = 0, b = c ^ 0 = c)

a ^= b (a = c ^ 0 = c, b = c)

Notice that at the end, you still end up with a = b = c. There are plenty of reasons not to use this approach, but that ain't one of them.

2 comments

He meant if they are the same variable, not the same value. (E.g., you pass pointers to your function.)

  int swap(int * a, int * b)
    {
    (*a)^=(*b);
    (*b)^=(*a);
    (*a)^=(*b);
    }
  int x = 15;
  int *y = &x;
  int *z = &x;

  swap(y,z);  //Now *y == 0
The case in which it breaks is when a and b are the same variable, not when they have the same value.