13

Suppose that there are two integers(int x, y;).
x is negative and y = 0x80000000.

Why does (x - y) not overflow while x + (-y) does?
Doesn't the computer do subtraction by addition?

learnvst
  • 15,455
  • 16
  • 74
  • 121
Yuu
  • 147
  • 6
  • How do you know it does? – lindelof Jun 08 '12 at 09:37
  • "Computer Systems, A Programmer's Perspective" Solution to Problem 2.32 (page 87) "...we will have -y also equal to TMin, and so function tadd_ok will consider there to be negative overflow any time x is negative. In fact, x-y does not overflow for these cases..." – Yuu Jun 08 '12 at 10:53

1 Answers1

8

To answer your first question, 0x80000000 (-2,147,483,648) represents minimum 32-bit value for signed integers. 2,147,483,647 is the maximum value. The magnitude of the maximum value is one less than the magnitude of the minimum value when stored using Two's Complement. Taking (-y) alone cannot be represented as it exceeds the maximum value (by 1). The final integer value of (x-y) is in range (given that x is negative) and can be represented by a 32-bit integer.

To answer your second question, subtraction is achieved by converting the number to be subtracted into its additive inverse. Given the potential for overflow in this situation, your compiler can get the correct result for (x-y) by doing -((-x)+y). However, this is pure speculation (it is the only way I can think of to do it safely).

learnvst
  • 15,455
  • 16
  • 74
  • 121