Visual Studio C++ 2008 / 2010 - 浮动 NaN 时中断

发布于 2024-10-07 15:28:41 字数 263 浏览 9 评论 0原文

有没有办法将 Visual Studio(刚刚从 2008 年升级到 2010 年)设置为在任何浮点数变为 NaN、QNAN、INF 等时中断,就像断言失败一样?

到目前为止,我一直在使用断言(x == x)技巧,但我宁愿使用隐式的东西,这样我就不必到处添加断言。

很惊讶我无法通过谷歌找到这个问题的答案。关于“浮点异常”的一些内容,但我不确定它们是否是同一件事,并且我尝试在 Visual Studio 中启用它们,但程序不会中断,直到由于 NaN 之后发生灾难性事件在执行中。

Is there any way to set up Visual Studio (just upgraded from 2008 to 2010) to break, as if an assertion failed, whenever any floating point number becomes NaN, QNAN, INF, etc?

Up until now I have just been using the assert(x == x) trick, but I would rather something implicit, so that I dont have to add assertions everywhere.

Quite surprised I can't find an answer to this via google. Some stuff about 'floating point exceptions', but I'm not sure if they are the same thing, and I've tried enabling them in Visual Studio, but the program doesn't break until something catastrophic happens because of the NaN later on in execution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

独自唱情﹋歌 2024-10-14 15:28:41

1) 进入项目选项并启用 /fp:strict (C/C++ -> Code Generation -> Floating Pint Model)。

2) 使用_controlfp设置浮点控制字(见下面的代码)。

#include <float.h>
unsigned int fp_control_state = _controlfp(_EM_INEXACT, _MCW_EM);

#include <math.h>

int main () {

    sqrtf(-1.0);    // floating point exception

    double x = 0.0;
    double y = 1.0/x;   // floating point exception

    return 0;
}

1) Go to project option and enable /fp:strict (C/C++ -> Code Generation -> Floating Pint Model).

2) Use _controlfp to set the floating-point control word (see code below).

#include <float.h>
unsigned int fp_control_state = _controlfp(_EM_INEXACT, _MCW_EM);

#include <math.h>

int main () {

    sqrtf(-1.0);    // floating point exception

    double x = 0.0;
    double y = 1.0/x;   // floating point exception

    return 0;
}
娇纵 2024-10-14 15:28:41

至少在 x86 上,当生成 NaN 等时,FPU 状态寄存器位之一会被设置。您可以设置一种方法,以便在发生下一个后续 FP 操作时抛出 H/W 异常,但这并不像您希望的那样快。但我不记得参考文献了。

At least on x86, when you generate an NaN etc, one of the FPU status register bits is set. There's a way you can set so that it throws a H/W exception on the next subsequent FP operation occurs, but that's not quite as soon as you hoped for. I can't recall the reference though.

慢慢从新开始 2024-10-14 15:28:41

我不确定这是否可以按照您想要的方式进行,但是您可以创建一个宏,将标记行中的代码包装到断言中,或者为此设置断点。

希望这有帮助

I am not sure if this is possible the way you want it, but You could create an macro which wraps the code in the marked line into an assert or which sets a breakpoint for this.

Hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文