为什么会产生浮点异常?
这是维基百科 SIGFPE 的第二个示例 页。
#include <limits.h>
int main(void)
{
volatile int x=INT_MIN;
volatile int y=-1;
x=x/y;
return 0;
}
它将 INT_MIN 的符号反转为正数。怎么可能是FPE呢?
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/y;
return 0;
}
It is inverting the sign to positive of INT_MIN. How can it be FPE?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
维基百科文章的答案是:
The Wikipedia article answers:
你读过维基页面吗?它可能是 FPE,但不是浮点异常。
Did you read the wiki page? It maybe an FPE but it's not a floating point exception.
正如您链接到的页面指出的那样,“虽然 SIGFPE 不一定涉及浮点运算,但无法在不破坏向后兼容性的情况下更改其名称”。
您收到信号的原因是二进制补码的工作方式。十六位二进制补码数的范围(例如)是
-32768..32767
。换句话说,65,536 个可能的值被映射到该范围。如果您尝试对
INT_MIN
取反,则没有任何表示形式可以为您提供正确的值(我们没有可用的32768
)。所有二进制补码的情况都是如此:八位为您提供
-128..127
,三十二位为您提供-2147483648..2147483647
。在所有这些情况下,
INT_MIN
没有正值等价物。有趣的是,ISO C 允许的其他两种编码方案(补码和符号/数值)在正值和负值之间具有直接的一对一映射。同样有趣的是,几乎没有人使用它们:-)
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 a32768
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 :-)