Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 576
Yuu Avatar asked Jun 08 '12 09:06

Yuu


1 Answers

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

like image 190
learnvst Avatar answered Sep 27 '22 23:09

learnvst