Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cwjcc!tut.cis.ohio-state.edu!att!cbnewsl!dfp From: dfp@cbnewsl.ATT.COM (david.f.prosser) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: <1594@cbnewsl.ATT.COM> Date: 23 Aug 89 19:00:36 GMT References: <17504@ut-emx.UUCP> Reply-To: dfp@cbnewsl.ATT.COM (david.f.prosser,sf,) Organization: AT&T Bell Laboratories Lines: 47 In article <17504@ut-emx.UUCP> pmaniac@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