Runtime error when dividing by -1
I have no doubt about the need to check division by zero. I've never heard of checking division for negative, though!
if( *y == 0 )
return 0; //undefined
else
return *x / *y;
x, y
are pointers to int32_t
, I include this detail in case of relevance.
At runtime, if *x==0x80000000, *y==0xffffffff
, I get the error (in Xcode):
EXC_ARITHMETIC (code = EXC_I386_DIV, subcode = 0x0)
All I can find on the internet are suggestions that it is division by zero, but as you can see from the test above, and I can see from the debug window, it is not.
What does the error mean and how can I fix it?
source to share
2's complement representation is asymmetric: there is one more negative number than a positive number, and that negative number has no positive counterpart. Therefore, negation MIN_INT
represents an integer overflow (where MIN_INT
is the value, the only 1-bit is the sign bit, 0x80000000 for 32-bit integers).
MIN_INT / -1
hence also arithmetic overflow. Unlike subtraction overflow (which is rarely checked), division overflow can cause a trap, and presumably what happens in your case.
And, yes, technically speaking, you have to check for overflow before division MIN_INT / -1
, because the result is undefined.
Note. ... In the general case of Intel x64 architecture, a division overflow traps in exactly the same way as division by 0. Vaguely, the corresponding Posix signal SIGFPE
, which is usually considered a "Floating-point Exception", although there is no floating point. The current Posix standard actually shines SIGFPE
as meaning "Erroneous Arithmetic Operation".
source to share