Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!gem.mps.ohio-state.edu!ginosko!uunet!virtech!cpcahil From: cpcahil@virtech.UUCP (Conor P. Cahill) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: <1066@virtech.UUCP> Date: 24 Aug 89 02:45:22 GMT References: <1061@virtech.UUCP> <990@m3.mfci.UUCP> Organization: Virtual Technologies Inc Lines: 47 In article <990@m3.mfci.UUCP>, karzes@mfci.UUCP (Tom Karzes) writes: > In article <1061@virtech.UUCP> cpcahil@virtech.UUCP (Conor P. Cahill) writes: > >In article , tg1e+@andrew.cmu.edu (Timothy R. Gottschalk) writes: > 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. I stand corrected. You know I was about to say what about unsigned values where the two operands added up to be greater than what can fit into the storage area, but I decided to try it on my machine before I opened my big mouth. Lucky I did. Using the following code: unsigned short i,j; i = 42000; j = 42001; printf("sizeof(i) = %d\n", sizeof(i)); printf("i = %u, j = %u\n", i, j); i += j; printf("i = %u, j = %u\n", i, j); j = i - j; printf("i = %u, j = %u\n", i, j); i -= j; printf("i = %u, j = %u\n", i, j); the output was: sizeof(i) = 2 i = 42000, j = 42001 i = 18465, j = 42001 i = 18465, j = 42000 i = 42001, j = 42000 I was about to scream "Compiler Error" when I realized that 18465 - 42001 does underflow back to 42000. So the original post does work as long as there is no hardware problems with decimal overflow. -- +-----------------------------------------------------------------------+ | Conor P. Cahill uunet!virtech!cpcahil 703-430-9240 ! | Virtual Technologies Inc., P. O. Box 876, Sterling, VA 22170 | +-----------------------------------------------------------------------+