swap(x,y)

Herman Rubin cik at l.cc.purdue.edu
Tue Aug 22 23:32:07 AEST 1989


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:
> 
>        /* begin swap */
>        x += y;
>        y = x - y;
>        x -= y;
>        /* end swap */
> 
>        Just curious...(this looks pretty valid) does anyone know an even
> simpler method?  I would never program this way -- it's more of a theory
> question.  I've been told that it can't be done (???).
> Tim Gottschalk
> Pgh, PA

As a function call, it is not worth while.  But for switching registers in
a tights situation on a machine without instruction overlap, it is likely to
be as fast as anything.  One needs three instructions, and since the operations
may be as fast as moves, no time is lost, compared to

        /* begin swap */
        temp = y;
        y = x;
        x = temp;
        /* end swap */

except that if x and y are the same, the second will work but not the first.
-- 
Herman Rubin, Dept. of Statistics, Purdue Univ., West Lafayette IN47907
Phone: (317)494-6054
hrubin at l.cc.purdue.edu (Internet, bitnet, UUCP)



More information about the Comp.lang.c mailing list