## How to swap two variables... ??

Post here if you don't find any other place for your post. But please, stay on-topic: algorithms, programming or something related to this web site and its services.

Moderator: Board moderators

pipo
New poster
Posts: 47
Joined: Tue May 11, 2004 6:43 pm
Location: Republic of Korea

### How to swap two variables... ??

hi all...

I got a quiz...

How to swap two variables ???

only use two variables and two statements...

In general, the code is following...

Code: Select all

``````temp = a;
a = b;
b = temp;
``````
how to swap two variables using only two variables and two statements ?? do not use a temporary variable.. and 3 statements...

Leonid
Experienced poster
Posts: 146
Joined: Thu Dec 22, 2005 5:50 pm
Contact:
Using bitwise operators you can do it like this:

Code: Select all

``a ^= b ^= a ^= b;``
Though I usually use STL provided swap function because it is faster to type and is more comprehentable, like that:

Code: Select all

``swap(a,b);``

pipo
New poster
Posts: 47
Joined: Tue May 11, 2004 6:43 pm
Location: Republic of Korea

I suggested you have to use just 2 statements..

it means you must use 2 equal signs...

I know using bitwise operators suggested by Leonid..

I'm sorry but it's not the wanted answer

PS.. Sorry for poor english

misof
A great helper
Posts: 430
Joined: Wed Jun 09, 2004 1:31 pm
If you can only do one assignment in one statement, it seems impossible -- after the first assignment, one of the variables is unchanged, the other has to have the new value, and thus one of the values is lost.

I think we need a more precise definition of what those "two statements" are allowed to be.
Technically,

Code: Select all

``````void swap(int &a, int &b) {
if (a>b) a--, swap(a,b), b++;
if (a<b) b--, swap(a,b), a++;
}
``````
can be considered to be two statements, and with no equal signs

If you don't like the if-s, you may go one step further:

Code: Select all

``````void swap(int &a, int &b) {
(a>b) && (a--, swap(a,b), b++);
(a<b) && (b--, swap(a,b), a++);
}
``````
Aren't those two C++ statements?

QulinXao
New poster
Posts: 29
Joined: Mon Apr 05, 2004 11:12 am

### same

buty of arifmetica is
function swap(var a,b:T):T;begin
a:=-(a+b);
b:=-(a+b);
a:=-(a+b);
end;

or on array a[0..1]

for i:=0 to 2 do a:=-(a[0]+a[1]);