subtraction between unsigned ints

Mark Brader msb at sq.sq.com
Sat Sep 9 11:41:54 AEST 1989


> >	unsigned int	u, v;
> >	long int	x;
> >	u=3; v=5;
> >	x=u-v;

> If long int is the same size as unsigned int, then the big number that
> results from subtraction will become signed.  On a two's-complement
> machine, yes the result will be -2.

No, it will be "implementation-defined behavior"; see the last part of
section 3.2.1.2.  (I assume that "corresponding signed integer" there is
meant to include other signed integral types of the same size as the
corresponding signed integer!  In any event, overflow situations involving
signed integer types are generally implementation-defined behavior.)

On a two's-complement machine where signed integers give modular arithmetic
with overflows ignored, i.e. the common case, yes the result is -2.
(Yes, I mean modular.  You can do arithmetic modulo 8 using the numbers
-4, -3, ..., +3 just as well as using 0, 1, ... 7, and similarly for any
other modulus, such as the 2-to-the-wordsize applicable here.)

> If long int is longer than unsigned int, then the big number that
> results from subtraction will remain a big number.

Correct.

-- 
Mark Brader			"A hundred billion is *not* infinite
SoftQuad Inc., Toronto		 and it's getting less infinite all the time!"
utzoo!sq!msb, msb at sq.com		-- Isaac Asimov, "The Last Question"

This article is in the public domain.



More information about the Comp.std.c mailing list