swap(x,y)
Tom Karzes
karzes at mfci.UUCP
Thu Aug 24 07:37:13 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.
This should only be a problem if your machine traps on integer overflow,
or if your hardware is broken and doesn't give the desired results in
the presence of integer overflow. Sane hardware will give you the correct
low-order bits of the result regardless of overflow. This will guarantee
that the above produces correct results, even if the intermediate results
overflow. So the statement about "throwing off the rest of the equations"
above is incorrect. In the case of 16-bit integers, you can think of the
entire process as an unsigned computation being performed mod 2**16 (the
only difference between signed and unsigned integer addition, subtraction,
and multiplication is the overflow conditions, provided your hardware always
gives you the correct low-order bits).
In your example, using 16-bit integers:
action x (decimal) (hex) y (decimal) (hex)
------ ----------------- -----------------
initial 18000 4650 19000 4a38
x += y -28536 9088 19000 4a38
y = x - y -28536 9088 18000 4650
x -= y 19000 4a38 18000 4650
More information about the Comp.lang.c
mailing list