John Regehr's blog post A Guide to Undefined Behavior in C and C++, Part 1 contains the following "safe" function for "performing integer division without executing undefined behavior":
int32_t safe_div_int32_t (int32_t a, int32_t b) {
if ((b == 0) || ((a == INT32_MIN) && (b == -1))) {
report_integer_math_error();
return 0;
} else {
return a / b;
}
}
I'm wondering what is wrong with the division (a/b) when a = INT32_MIN and b = -1. Is it undefined? If so why?
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!
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