Welcome to G4EF

I know what you are trying to ask, and I am answering what you want to hear ::
Here is how you can do it without using any arithmetic op.s and any temp. var. :
Code: C++
a = a^b;
b = b^a;
a = a^b;
Or in a single line :
Code: C++
a^=b^=a^=b;

But this is **NOT** the best way, because suppose you define this :
Code: C++
void swap(int &x, int &y)
{    x^=y^=x^=y;    }
This would work fine for calls like swap(A,B), where A = 2 and B = 3 say.
But for calls like swap(A,A) or swap(A,B) where B=A, it would lead to entire loss of data (variable's contents).
So, be careful while using it.


Again, that won't work for data-types like float, double, structs, classes etc ...
So, you should mention in your question that the target vars are of the type int.

A generic swap function can be :
Code: C++
template <class TYPE>
void swamp(TYPE &var1, TYPE &var2) {
    TYPE var_temp = var1;
    var1 = var2;
    var2 = var_temp;
}
That one uses a temp. var., 'coz there's no way out.

You can do it this way too :
Code: C++
#include <algorithm>
. . .
. . .
. . .
swap(x,y);
. . .
. . .
. . .
This one doesn't seem to use any arithmetic op.s or temp var.s, but works with a temp var. in the background

Last edited by SaswatPadhi; 30Sep2009 at 15:31.. Reason: Added lots of things :p
abhisek dash like this