swap(x,y)

Conor P. Cahill cpcahil at virtech.UUCP
Wed Aug 23 08:50:46 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:
>        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.

-- 
+-----------------------------------------------------------------------+
| Conor P. Cahill     uunet!virtech!cpcahil      	703-430-9240	!
| Virtual Technologies Inc.,    P. O. Box 876,   Sterling, VA 22170     |
+-----------------------------------------------------------------------+



More information about the Comp.lang.c mailing list