### Operator ^=

I came across an article on macros, and i noticed whoever wrote it used
this
 `` `` ``#define SWAP(x,y) x ^= y; y ^= x; x ^= y; ``

to swap two values. I couldn't understand why it worked, and i still don't know.
So i did some calculations, and either whoever wrote that article is wrong, or
i messed up somewhere trying to solve this.
 ``1234567891011121314151617181920`` `````` int x = 10, y = 5; SWAP (x, y); 1010^= // x^= 0101 // y = 11001 = 1111 + 1010 = x^=y = 1+8+16+ 10 = 35 = x 00101^= //y^= 11001 //x = 100001 = 00101 + 11100 = 4+8+16 + 5 = 33 = y^=x = y = 33 011001^= //x^= 100001 //y = 111000 = 8 + 16 + 32 = x^=y = x = 56``````

I wonder if i have misinterpreted the concept of operator^=,
isn't it like a += only it's Xor instead of addition?
Last edited on
 isn't it like a += only it's Xor instead of addition?

Yes... but do you understand what xor does? Because your example is wrong.

 ``1234`` ``````0 XOR 0 = 0 0 XOR 1 = 1 1 XOR 0 = 1 1 XOR 1 = 0``````

XOR has the property of neutralizing itself. That is `a ^ a` will be zero, no matter what a is.

This works as follows:

 ``12345678`` ``````int X = x; // capital X is the ORIGINAL x int Y = y; // capital Y is the ORIGINAL y x ^= y; // at this point: x = X^Y and y = Y y ^= x; // at this point: x = X^Y and y = Y ^ X ^ Y .... the Ys cancel out, so y = X x ^= y; // at this point: x = X^Y^X ... the Xs cancel out, so X=y and y=X // so the swap is complete ``````

If you plug in numbers, it works the same:

 ``123456`` ``````x = 10; // 1010 y = 5; // 0101 x ^= y; // 1010 ^ 0101 = 1111... so x = 15 (%1111) y ^= x; // 0101 ^ 1111 = 1010... so y = 10 x ^= y; // 1111 ^ 1010 = 0101... so x = 5 ``````
 Yes... but do you understand what xor does? Because your example is wrong.

The resulting bit becomes 1 if the two bits being compared are different, right?

I think i see the problem now.
When i calculated i did something more similar to this: x+=x^y...

Thank you for showing me the path, your example was helpful.
Just to add: you should never do this, as it is obscure and confusing at best, only works on integer types, and can also confuse the optimizer so you get slower swaps.
Topic archived. No new replies allowed.