Question

I came across this in a computer architecture textbook:

Subtracting a strictly negative integer from another strictly negative integer (in two's complement) will never overflow.

The textbook doesn't go on to explain this assertion. It piqued my curiosity.

Why is this statement true?

Was it helpful?

Solution

Here's how it works for 32 bit integers. It works the same for any other bit length.

The largest negative number is -1.

The smallest negative number is -2^31.

Overflow occurs if a result is greater than or equal to 2^31, or smaller than -2^31.

You get the largest result of a subtraction by subtracting the smallest number from the largest one. -1 - (-2^31) = 2^31 - 1. This is small enough.

You get the smallest result of a subtraction by subtracting the largest number from the smallest one. -2^31 - (-1) = -(2^31 - 1). This is greater than -2^31.

OTHER TIPS

Since the range of negative signed integers is -1 to -(MAX_INT+1), the range of possible differences between two such numbers is -MAX_INT to MAX_INT. Since this range is easily representable (remember that the full signed integer range is -(MAX_INT+1) to MAX_INT), then evidently there can never be an overflow.

the range of numbers that can be obtained by such a substraction is [MIN_INT+1,MAX_INT], and thus will never overflow.
why?
let there be MIN_INT <= x,y < 0 so: MIN_INT = MIN_INT-0 < x-y < 0-MIN_INT = MAX_INT+1
And thus MIN_INT < x-y < MAX_INT + 1 note that 'strong' < prevent overflow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top