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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 thatxis 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).