gpt4 book ai didi

c - 使用 Infinity 和 NaN 禁用异常

转载 作者:行者123 更新时间:2023-12-01 22:09:55 24 4
gpt4 key购买 nike

我有一个巨大的项目(不是我构建的),允许具有 InfinityNaN 值。虽然这是允许的,但这是不可取的。我read这些值是由此类操作生成的:

1/0 = ∞
log (0) = -∞
sqrt (-1) = NaN

除此之外,当达到它们时,应该抛出 FP 异常

如果我的项目允许使用 NaNInfinity 进行操作,我认为 SIGFPE 会在某个地方处理,但我搜索了整个项目但找不到它。

还有其他方法可以禁用此异常吗?我的目标是能够检测到此类值的第一次出现。

编辑:我使用的是 Windows,我打算启用该信号,但在启用之前,我想了解它是否被禁用。

最佳答案

我认为您不会遇到您所谈论的问题。默认情况下,不会引发 FP 异常。从 Windows documentation :

By default, the system has all FP exceptions turned off. Therefore, computations result in NAN or INFINITY, rather than an exception. Before you can trap floating-point (FP) exceptions using structured exception handling, you must call the _controlfp_s C run-time library function to turn on all possible FP exceptions. To trap only particular exceptions, use only the flags that correspond to the exceptions to be trapped. Note that any handler for FP errors should call _clearfp as its first FP instruction. This function clears floating-point exceptions.

GCC 也是如此,其中 documentation说:

When exceptions occur (when exceptions are raised, in the language of the standard), one of two things can happen. By default the exception is simply noted in the floating-point status word, and the program continues as if nothing had happened. The operation produces a default value, which depends on the exception [...]). Your program can check the status word to find out which exceptions happened.

要在 Windows 环境中启用异常(这将停止程序的执行),您可以尝试类似的操作

#include <float.h>

int main() {
_clearfp();
unsigned int current_word = 0;
_controlfp_s(&current_word, ~_EM_ZERODIVIDE, _MCW_EM);
double div = 0.;
double f = 1. / div;
}

对于非阻塞解决方案,请尝试使用 fenv.h,如所述 here在 cppreference.com 上。

关于c - 使用 Infinity 和 NaN 禁用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53225506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com