swap(x,y)

david.f.prosser dfp at cbnewsl.ATT.COM
Thu Aug 24 05:00:36 AEST 1989


In article <17504 at ut-emx.UUCP> pmaniac at walt.cc.utexas.edu (Noah Friedman) writes:
>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.

Because it is wrong.

This call to swap passes pointers to integers converted to pointer-to-
double type.  This does not change the objects pointed-to in any manner.
The *x and *y expressions within swap cause completely undefined behavior.

With most architectures, double objects are bigger than int objects.
The *x and *y subexpressions will be accessing bytes outside of the
ints a and b.  Moreover, the bit patterns in the representation for int
values most likely has little to do with that used by doubles.  It is
quite likely that floating exceptions will occur.  Finally, the initial
premise (using doubles will prevent problems with the add and subtract
swap) is false: it is not guaranteed that precision will not be lost
converting from ints to doubles.  For example, consider an architecture
that has ints and doubles in identical-size objects (possible with ANSI C).
Given that there have to be some bits for the exponent, some loss of
precision is likely.

I do agree with the letter writer than these "tricks" for exchanging
values are all not worth the cost, except in extreme conditions such
as the classic linked list walk and return that XORs pointers so that
O(n) extra pointers don't need to be stored.

Dave Prosser



More information about the Comp.lang.c mailing list