Search code examples
theory

(Integer's max value + 1) + (Integer's max value + 1) = 0?


Basically, an integer's max value is 2147483647 and the min value is -2147483648, which makes when you add 1 to the max value of integer, it becomes to the min value of integer.

If I put the max value of int(I use 'max' as below):

(max+1) + (max+1)

the result is 0.

Apparently the plus sign reverse into minus. Why? What is the theory behind this?


Solution

  • Since you already understand the topic of integer overflow/underflow, let's look at the math.

    For the sake of argument let's just say that the minimum integer is -8 and the maximum is 7. Therefore we would get the following reduction:

    given (max + 1) + (max + 1) using integer overflow/underflow
    = (7 + 1) + (7 + 1)
    = (-8) + (-8)
    = -8 + -1 + -7
    = 7 + -7
    = 0
    

    When you add -1 to -8 you are actually subtracting 1 from -8 giving you a result of -9. Because this is an underflow the answer becomes 7. So when you subtract 7 from 7 you get 0.

    If we looked at it in binary using twos' complement, it looks something like this:

    given (max + 1) + (max + 1) using integer overflow/underflow
    = (0111 + 0001) + (0111 + 0001)
    = (1000) + (1000)
    = 1000 + 1111 + 1001
    = 0111 + 1001
    = 0000
    

    The binary math really depends on how you're storing the sign of the integer. Like I said, we are using twos' compliment here, but there are other methods like ones' compliment, and Excess-K.