Yuu
Yuu

Reputation: 147

Subtraction without overflow?

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?

Upvotes: 13

Views: 1646

Answers (1)

learnvst
learnvst

Reputation: 16193

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).

Upvotes: 8

Related Questions