[Ilugc] Re: Re: [C] Swap integers without using temp variable

  • From: sanand@xxxxxxxxxx (Sridharan Anand)
  • Date: Tue Apr 19 18:23:25 2005

On Tue, 19 Apr 2005 17:12:50 +0530, "Binand Sethumadhavan"
<binand@xxxxxxxxx> wrote:

On 4/19/05, Sridharan Anand
<sanand@xxxxxxxxxx> wrote:
      a ^= b ^= a ^= b;

I hate to be such a pedant, but this causes undefined behaviour due to
the absence of a sequence point between successive assignments.  In
other words, the expression contains multiple ambiguous side effects. I
forget

Spot on. Even its expanded (and compliant) version:

a ^= b; b ^= a; a ^= b;

will grok if you call it as swap(v,v).
                              ^^^^^^^^^
Just a nit.  You also meant to pass pointers, presumably,
and to check equivalence inside swap ()?  Then it would grok.

The best way of doing it is:

tmp = a;
a = b;
b = tmp;

and the rest are only of academic interest and should not really be in
robust programs.

Absolutely.  Totally agree with you here.  You could have said
`the One True Way of doing it is ...' but that would have started a flame
war :-D ! 

Later,

Anand.

Other related posts: