Shubh Shubh - 1 year ago 71
C Question

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

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;

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download