swap(x,y)

Noah Friedman pmaniac at walt.cc.utexas.edu
Wed Aug 23 20:19:39 AEST 1989


In article <1061 at virtech.UUCP> cpcahil at virtech.UUCP (Conor P. Cahill) writes:
>In article <MYwDEFy00WB842JEUx at andrew.cmu.edu>, tg1e+ at andrew.cmu.edu (Timothy R. Gottschalk) writes:
>>        To swap two variables x,y in C without using a temporary variable:
>>        x += y;
>>        y = x - y;
>>        x -= y;
>
>The problem with this method is that it will be easy to overflow the
>variables in the first statement.   For example if x and y are short (16 bit)
>integers and x contains 18,000 and y contains 19,000 the x will overflow to 
>negative territory on the first assignment and throw off the rest of the 
>equations.  If x & y are large enough the overflow could just be lost.

To prevent this problem, why not cast the arguments as doubles?

void swap(double *x, double *y) 
{
    *x += *y;
    *y = *x - *y;
    *x -= *y;
}

func()
{
 int a, b;

    ...
    swap((double *) &a, (double *) &b);
    ...
}

This function should then work with any type, providing you type cast.
Of course, there is the possibility of loss of precision, but this
only applies to floating point variables.

Personally I'd write the swap function the traditional way, using 3
variables. And if I had a C++ compiler I'd overload swap() to handle
any type.

-=*=-----
pmaniac at walt.cc.utexas.edu (Noah Friedman)

Any opinions expressed in this article are entirely my own and are not
necessarily those of any official organization, including UT Austin.

for (eat=food; food != food_val(DOG); eat++, food--) ;
-=*=-----



More information about the Comp.lang.c mailing list