有没有一种方法可以告诉gcc在运行时对导致计算结果为NaN
或(-)inf
的计算抛出类似于除以零一样的SIGFPE信号?
我尝试了-fsignaling-nans
标志,但似乎没有用。
有没有一种方法可以告诉gcc在运行时对导致计算结果为NaN
或(-)inf
的计算抛出类似于除以零一样的SIGFPE信号?
我尝试了-fsignaling-nans
标志,但似乎没有用。
#define _GNU_SOURCE
#include <fenv.h>
int main(void) {
double x, y, z;
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
x = 1e300;
y = 1e300;
z = x * y; /* should cause an FPE */
return 0;
}
需要注意的是,在某些设定下,异常实际上可能是在理论上应该引起异常的下一个浮点操作之后才会生成,因此有时需要执行无操作的浮点操作(例如乘以1.0)来触发异常。
feenableexcept
未定义。解决方法是使用Win32平台的_controlfp
,代码如下:#undef __STRICT_ANSI__ // _controlfp is a non-standard function documented in MSDN
#include <float.h>
#include <stdio.h>
int main()
{
_clearfp();
unsigned unused_current_word = 0;
// clearing the bits unmasks (throws) the exception
_controlfp_s(&unused_current_word, 0, _EM_OVERFLOW | _EM_ZERODIVIDE); // _controlfp_s is the secure version of _controlfp
float num = 1.0f, den = 0.0f;
float quo = num / den;
printf("%.8f\n", quo); // the control should never reach here, due to the exception thrown above
}