Is there any difference between these two like one is faster or smaller? Benefit of using one over another?
Swapping using XOR operator
int a, b;
a ^= b ^= a ^= b;
Swapping using third variable
int a, b, temp;
temp = a;
a = b;
b = temp;
Is there any difference between these two like one is faster or smaller? Benefit of using one over another?
int a, b;
a ^= b ^= a ^= b;
int a, b, temp;
temp = a;
a = b;
b = temp;
(The behaviour of both of your snippets is undefined since you're reading uninitialised variables).
Don't ever use XOR swap.
The way you have it (a^=b^=a^=b;
) is actually undefined behaviour as you are modifying a variable more than once between sequencing points. The compiler reserves the right to eat your cat.
Trust the compiler to make optimisations.
It only works for integral types.
It would fail if a
and b
refer to the same object: if you use this method for swapping objects passed by address e.g. void xorSwap(int *x, int *y)
, a correct implementation requires an if
block.
XOR swapping
is not clear: most people won't understand what your code is doing, and it is considered to be cryptic.
Self-explaining code is always better to have, so unless there is a huge performance issue and benchmarking proves the xor method to be faster, prefer using a third variable.