Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between XOR swapping algorithm and swapping using third variable? [duplicate]

Tags:

c

swap

xor

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;
like image 535
Shubh Avatar asked Jun 14 '26 21:06

Shubh


2 Answers

(The behaviour of both of your snippets is undefined since you're reading uninitialised variables).

Don't ever use XOR swap.

  1. 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.

  2. Trust the compiler to make optimisations.

  3. It only works for integral types.

  4. 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.

like image 62
Bathsheba Avatar answered Jun 17 '26 11:06

Bathsheba


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.

like image 25
blue112 Avatar answered Jun 17 '26 09:06

blue112



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!