swap(x,y)

News system news at ism780c.isc.com
Fri Aug 25 06:01:00 AEST 1989


In article <3040 at solo5.cs.vu.nl> maart at cs.vu.nl (Maarten Litmaath) writes:
>jsb at advdev.LBP.HARRIS.COM (FLEA) writes:
>\In article <8350 at boring.cwi.nl> tromp at piring.cwi.nl (John Tromp) writes:
>\:		 (Timothy R. Gottschalk) writes:
>\...
>\:>       x += y;
>\:>       y = x - y;
>\:>       x -= y;
>\...
>\Sorry, folks, both of these are illegal if x and y are pointers.
>
>Or if they're structs! :-)

It is obvious to the casual observer that the above is illegal if the
operations + and - are not defined for the data.  The question really is: for
the case where the program segment (as written) compiles, will it swap the
values of x and y.  The answer is that it will work on two's complement
binary machines that ignore overflow and carry out provided x and y are the
same integral type.  It does not work when the types differ (for example
char x; long y;).  It also does not work for all values of floating types.

But most important, it is a bad piece of code for two reasons.  1) it is
obtuse and  2) it requires more space and time than the simpiler:

     temp=x; x=y; y=temp;

As may have been pointed the EXOR method may be faster then the above for
a machine like the 370 that provides a memory to memory EXOR operation on
data blocks.  But there is no way to express such an operation in C.

     Marv Rubinstein



More information about the Comp.lang.c mailing list