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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With