Page 1 of 1

Exchanging two integers

Posted: Thu Jun 24, 2004 1:31 pm
by Tomislav Novak
Hi!

Is there a way I could exchange a and b (both a and b are integers) without using a temporary variable, so a = b and b = a? Some oneliner, or macro?
I think I saw once something with XOR, but I can't really remember what it was...

Thanks.

Posted: Thu Jun 24, 2004 2:59 pm
by Rodrigo
Sure, using XOR

a ^= b ^= a ^= b;

or additions and subtractions:

a += b; a -= b = a - b;

I think there was a third way, but I can't remember it now.

Posted: Thu Jun 24, 2004 5:49 pm
by Tomislav Novak
Rodrigo wrote: a ^= b ^= a ^= b;

or additions and subtractions:

a += b; a -= b = a - b;
Thanks! ;) That's what I was looking for...

Posted: Sat Jun 26, 2004 4:48 am
by junjieliang
The third way that I know of is similar to the addition/subtraction method:

a = a * b;
b = a / b;
a = a / b;

Well then again this method is real stupid... you can get overflow and precision errors very easily. Just for fun I knowing it, but don't use it in real programs! :)

Posted: Sat Jun 26, 2004 3:07 pm
by Krzysztof Duleba
Actually doing anything else than swaping the integers using a temporary variable is slower and shouldn't be used in code at all.
For stl classes, std::swap(T, T) is the best choice. For instance, swaping two lists is O(1).

Posted: Wed Jun 01, 2005 3:13 pm
by jakabjr
besides, this is defined by ANSI C as undetermination:
a ^= b ^= a ^= b;
since u are trying to modify and access a variable in at the same point of execution.
it might work, but it's not portable.