tags:

views:

99

answers:

4

I just saw this code here.

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;
  }
}

Just wondering what is wrong with the division (a/b) when a = INT32_MIN and b = -1. Is it undefined? If so why?

+10  A: 

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.

muddybruin
Yes. this makes sense.
chappar
Correct. This is the only possible pair of values that will overflow when dividing 32-bit integers.
LukeH
A: 

Because INT32_MIN is defined as (-INT32_MAX-1) = -(INT32_MAX+1) and when divided by -1, this would be (INT32+MAX) => there is an integer overflow. I must say, that is a nice way to check for overflows. Thoughtfully written code. +1 to the developer.

Gangadhar
I don't know that replacing the division operator with a function named "save_div_in32_t" is "thoughtful"...
meagar
The thoughtful comment was for taking into consideration the integer overflow. I have seen very few programmers taking care about these situations (of course most developers work on application specific code and let the framework handle these, but once in a while one is bound to be bitten by these kinds of situations).
Gangadhar
+2  A: 

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!

Justin Ardini
I didn't see your answer when I wrote my comment under the question. +1
AraK
+2  A: 

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.

AShelly