Why is this generating Floating point exception?
This is the second example of wikipedia SIGFPE page.
#include <limits.h>
int main(void)
{
volatile int x=INT_MIN;
volatile int y=-1;
x=x开发者_StackOverflow社区/y;
return 0;
}
It is inverting the sign to positive of INT_MIN. How can it be FPE?
The Wikipedia article answers:
... triggers the signal because the quotient, a positive number, is not representable.
INT_MIN / -1 = -INT_MIN
= INT_MAX + 1
=> invalid number
=> floating point exception (FPE)
Did you read the wiki page? It maybe an FPE but it's not a floating point exception.
Although SIGFPE does not necessarily involve floating-point arithmetic, there is no way to change its name without breaking backward compatibility.
As that page you link to points out, "although SIGFPE does not necessarily involve floating-point arithmetic, there is no way to change its name without breaking backward compatibility".
The reason you're getting the signal is because of the way two's complement numbers work. The range for a sixteen bit two's complement number (for example) is -32768..32767
.
In other words, the 65,536 possible values are mapped to that range. If you try to negate INT_MIN
, there is no representation that will give you the correct value (we don't have a 32768
available to us).
Ths is the case for all two's complement numbers: eight bits gives you -128..127
, thirty two bits gives you -2147483648..2147483647
.
In all those cases, INT_MIN
does not have a positive equivalent.
Interestingly, the other two encoding schemes allowed for by ISO C (one's complement and sign/magnitude) have a direct one-to-one mapping between positive and negative values). Equally interesting, almost no-one uses them :-)
精彩评论