简体   繁体   English

为什么整数除以零会导致浮点异常?

[英]Why does integer division by zero result in a floating point exception?

Division by zero in a C program results in abnormal termination with the error message Floating point exception (core dumped) . 在C程序中除以零会导致异常终止,并显示错误消息Floating point exception (core dumped) This is unsurprising for floating point division, but why does it say this when integer division by zero occurs? 这对于浮点除法并不足为奇,但为什么在整数除以零时会这样说呢? Does integer division actually use the FPU under the hood? 整数除法实际上是否使用引擎盖下的FPU?

(This is all on Linux under x86, by the way.) (顺便说一下,这都是在x86下的Linux上。)

Does integer division actually use the FPU under the hood? 整数除法实际上是否使用引擎盖下的FPU?

No, Linux just generates SIGFPE in this case too (it's a legacy name whose usage has now been extended). 不,Linux也只是在这种情况下生成SIGFPE(它是一个遗留名称,其使用现已扩展)。 Indeed, the Single Unix Specification defines SIGFPE as " Erroneous arithmetic operation ". 实际上,单Unix规范将SIGFPE定义为“ 错误的算术运算 ”。

man signal mentions: man signal提到:

Integer division by zero has undefined result. 整数除零具有未定义的结果。 On some architectures it will generate a SIGFPE signal. 在某些架构上,它将生成SIGFPE信号。 (Also dividing the most negative integer by -1 may generate SIGFPE.) (也将最负整数除以-1可能会生成SIGFPE。)

My guess at a historical explanation for this would be that the original unix hardware didn't generate a trap on integer division by zero, so the name SIGFPE made sense. 我对此的历史解释的猜测是原始的unix硬件没有在整数除以零上生成陷阱,因此SIGFPE的名称是有意义的。 (PDP assembly programmers, confirm?) Then later when the system was ported (or in the case of Linux, reimplemented) to hardware with an integer division-by-zero trap, it was not considered worthwhile to add a new signal number, so the old one acquired a new meaning and now has a slightly confusing name. (PDP组装程序员,确认?)然后,当系统被移植(或者在Linux的情况下,重新实现)到具有整数被零除陷阱的硬件时,不值得添加新的信号编号,所以旧的获得了一个新的含义,现在有一个稍微混乱的名字。

There could be many different implementation-specific reasons for that. 可能有许多不同的特定于实现的原因。

For example, the FPU unit on x86 platform supports both floating point and integer formats for reading arguments and writing results. 例如,x86平台上的FPU单元支持浮点和整数格式,用于读取参数和写入结果。 Back when the platform itself was 16-bit, some compilers used the FPU to perform division with 32-bit integer operands (since there's no precision loss for 32-bit wide data). 当平台本身为16位时,一些编译器使用FPU来执行32位整数操作数的划分(因为32位宽数据没有精度损失)。 Under such circumstances there would be nothing unusual in getting a genuine FPU error for invalid 32-bit integer division. 在这种情况下,对于无效的32位整数除法,获得真正的FPU错误没有什么异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM