How to swap two numbers without using temp variables or arithmetic operations?

Vishwanath Dalvi picture Vishwanath Dalvi · Sep 5, 2010 · Viewed 57.3k times · Source

This equation swaps two numbers without a temporary variable, but uses arithmetic operations:

a = (a+b) - (b=a);

How can I do it without arithmetic operations? I was thinking about XOR.

Answer

BiGYaN picture BiGYaN · Sep 5, 2010

In C this should work:

a = a^b;
b = a^b;
a = a^b;

OR a cooler/geekier looking:

a^=b;
b^=a;
a^=b;

For more details look into this. XOR is a very powerful operation that has many interesting usages cropping up here and there.