代码之家  ›  专栏  ›  技术社区  ›  Jordan Lewis

我能让gcc告诉我在运行时计算结果是NaN还是inf吗?

  •  17
  • Jordan Lewis  · 技术社区  · 16 年前

    有没有办法告诉gcc抛出SIGFPE或类似的东西来响应导致 NaN (-)inf 在运行时,就像被零除一样?

    我试过了 -fsignaling-nans 旗子,似乎没用。

    2 回复  |  直到 9 年前
        1
  •  24
  •   Mark Dickinson Alexandru    16 年前

    feenableexcept 函数来自 fenv.h . 这个 _GNU_SOURCE

    #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)来触发异常。

        2
  •  5
  •   legends2k    12 年前

    在mingw4.8.1(用于Win32的GCC)上,我看到 feenableexcept _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
    }