Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!gem.mps.ohio-state.edu!ginosko!uunet!cs.utexas.edu!ut-emx!walt.cc.utexas.edu!pmaniac From: pmaniac@walt.cc.utexas.edu (Noah Friedman) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Summary: Why not pass the variables to swap as double pointers? Message-ID: <17504@ut-emx.UUCP> Date: 23 Aug 89 10:19:39 GMT References: <1061@virtech.UUCP> Sender: news@ut-emx.UUCP Reply-To: pmaniac@walt.cc.utexas.edu (Noah Friedman) Organization: The University of Texas at Austin, Austin, Texas Lines: 47 Disorganization: Excessive In article <1061@virtech.UUCP> cpcahil@virtech.UUCP (Conor P. Cahill) writes: >In article , tg1e+@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. 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. Personally I'd write the swap function the traditional way, using 3 variables. And if I had a C++ compiler I'd overload swap() to handle any type. -=*=----- pmaniac@walt.cc.utexas.edu (Noah Friedman) Any opinions expressed in this article are entirely my own and are not necessarily those of any official organization, including UT Austin. for (eat=food; food != food_val(DOG); eat++, food--) ; -=*=-----