What is wrong with INT32_MIN/-1?
I think it's because the absolute value of INT32_MIN is 1 larger than INT32_MAX. So INT32_MIN/-1 actually equals INT32_MAX + 1 which would overflow.
So for 32-bit integers, there are 4,294,967,296 values.
There are 2,147,483,648 values for negative numbers (-2,147,483,648 to -1).
There is 1 value for zero (0).
There are 2,147,483,647 values for positive numbers (1 to 2,147,483,647) because 0 took 1 value away from the positive numbers.
This is because int32_t
is represented using two's-complement, and numbers with N
bits in two's-complement range from −2^(N−1)
to 2^(N−1)−1
. Therefore, when you carry out the division, you get: -2^(31) / -1 = 2^(N-1)
. Notice that the result is larger than 2^(N-1)-1
, meaning you get an overflow!
The other posters are correct about the causes of the overflow. The implication of the overflow on most machines is that INT_MIN / -1 => INT_ MIN. The same thing happens when multiplying by -1. This is an unexpected and possibly dangerous result. I've seen a fixed-point motor controller go out of control because it didn't check for this condition.