According to this link, performing INT_MIN / -1 division operation will result in the program to terminate in i386 CPUs. My processor is of 32-bit architecture and I use GCC compiler. I have done the following experiments to check it.
int a = INT_MIN;
int b = -1;
int c = a / b;
printf("%d\n",c);
As per the information specified in the link mentioned above this program gets terminated throwing a Floating point exception. But it wasn't the same when I tried it in a different manner.
int c = INT_MIN / -1;
printf("%d\n",c);
The compiler threw the following warning after compiling this program.
iso.c: In function ‘main’:
iso.c:6:18: warning: integer overflow in expression [-Woverflow]
int c = INT_MIN / -1;
_____________^
But I got the output -2147483648. Once again I did more two experiments.
int a = INT_MIN;
int b = -1;
printf("%d\n",a / b);
This was a floating point exception.
printf("%d\n",INT_MIN / -1);
This threw the following compiler warning.
iso.c: In function ‘main’:
iso.c:6:24: warning: integer overflow in expression [-Woverflow]
printf("%d\n",INT_MIN / -1);
__________________^
And the output of this program was again -2147483648.
After doing all these experiments, I have noticed that result of division operation done directly on constants differs from the result of the division operation done on variables. So what exactly is making this difference?
Both results are acceptable according to standard. Draft n1256 for C99 says (emphasize mine):
6.5 Expressions
...
5 If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.
In 2's complement integer representation, INT_MIN/-1
is INT_MAX + 1
so the operation invokes Undefined Behaviour, so any result (including crash) is acceptable
As explained by @tilz0R in his comment, when the values are passed in variables, the operation is executed at run time and raises a SIGFPE signal. But when the operation only involves compile time constants, the operation is executed by the compiler at compiler time. In gcc implementation, the compiler protect itself against the error and simply uses its best represention for INT_MAX + 1
. In a 32 bit 2's complement implementation, INT_MAX is 0x7fffffff, so INT_MAX + 1 is (after signed overflow) 0x80000000 or INT_MIN again (-2147483648)