swap(x,y)

Conor P. Cahill cpcahil at virtech.UUCP
Thu Aug 24 12:45:22 AEST 1989


In article <990 at m3.mfci.UUCP>, karzes at mfci.UUCP (Tom Karzes) writes:
> In article <1061 at virtech.UUCP> cpcahil at virtech.UUCP (Conor P. Cahill) writes:
> >In article <MYwDEFy00WB842JEUx at andrew.cmu.edu>, tg1e+ at 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     |
+-----------------------------------------------------------------------+



More information about the Comp.lang.c mailing list