Exchanging two integers

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
Tomislav Novak
New poster
Posts: 44
Joined: Fri Feb 20, 2004 5:52 pm

Exchanging two integers

Post 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.
Rodrigo
New poster
Posts: 14
Joined: Sun Jul 07, 2002 12:03 am
Location: Brazil
Contact:

Post 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.
Tomislav Novak
New poster
Posts: 44
Joined: Fri Feb 20, 2004 5:52 pm

Post 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...
junjieliang
Experienced poster
Posts: 169
Joined: Wed Oct 31, 2001 2:00 am
Location: Singapore

Post 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! :)
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post 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).
jakabjr
Learning poster
Posts: 56
Joined: Wed Mar 23, 2005 9:21 pm
Location: Timisoara, Romania

Post 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.
Understanding a problem in a natural way will lead to a natural solution
Post Reply

Return to “C”