Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!cs.utexas.edu!uunet!mfci!karzes From: karzes@mfci.UUCP (Tom Karzes) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: <990@m3.mfci.UUCP> Date: 23 Aug 89 21:37:13 GMT References: <1061@virtech.UUCP> Sender: karzes@mfci.UUCP Reply-To: karzes@mfci.UUCP (Tom Karzes) Organization: Multiflow Computer Inc., Branford Ct. 06405 Lines: 33 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. 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