0

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?

Paul R
  • 208,748
  • 37
  • 389
  • 560
David Chouinard
  • 6,466
  • 8
  • 43
  • 61
  • 2
    For the same reason that adding a negative integer and a positive integer will never overflow. – Hot Licks Sep 25 '11 at 16:12
  • That doesn't clear it up. Care to explain? – David Chouinard Sep 25 '11 at 16:15
  • 3
    Think about it -- when you add a negative integer to a positive integer, the result must be somewhere between your two starting values. Therefore it will be representable in the same number of bits as the starting values. For two negatives subtracted it's the same thing -- just consider that you're adding the "minus" of one number to the other, making it the addition of a positive and a negative. – Hot Licks Sep 25 '11 at 20:34
  • @Daniel That's a _great_ explanation. Much appreciated! – David Chouinard Sep 26 '11 at 11:03

3 Answers3

2

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.

Jeffrey Sax
  • 10,253
  • 3
  • 29
  • 40
0

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.

amit
  • 175,853
  • 27
  • 231
  • 333
0

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.

Paul R
  • 208,748
  • 37
  • 389
  • 560