Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with INT32_MIN/-1?

Tags:

c

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?

like image 876
chappar Avatar asked Aug 18 '10 15:08

chappar


2 Answers

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.

like image 146
muddybruin Avatar answered Oct 05 '22 05:10

muddybruin


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!

like image 43
Justin Ardini Avatar answered Oct 05 '22 04:10

Justin Ardini