Re: swap two integers without using a tmp variable?

From: Mike Smith (mike_UNDERSCORE_smith_at_acm.DOT.org)
Date: 06/22/04


Date: Tue, 22 Jun 2004 13:52:44 -0400

Richard Herring wrote:

> In message <976e0586.0406220444.4ed62241@posting.google.com>, Steve
> <ngsteve@my-deja.com> writes
>
>> The xor solution was really elegant. I would not have thought about it
>> and never knew it could be done this way.
>> X XOR Y XOR Y = X (assign in y variable, cancel out both Y)
>> X XOR Y XOR X = Y (assign in x variable, cancel out both X)
>
>
> And it DOESN'T WORK (no apologies for shouting) if X and Y are both
> references to the same object. Don't do it!

That's simple enough to fix:

void xor_swap(int &a, int &b)
{
   if (a != b)
   {
     b = a ^ b;
     a = b ^ a;
     b = a ^ b;
   }
}

There's still no good reason to do it, of course.

--
Mike Smith


Relevant Pages