执行期间检测下溢
有没有办法在执行过程中自动检测下溢?
具体来说,我认为应该有一个编译器选项来生成代码,在可能导致下溢和类似错误的数学运算之后立即检查它们。
我说的是 G++ 编译器。
Is there any way to detect underflow automatically during execution?
Specifically I believe there should be a compiler option to generate code that checks for underflows and similar falgs right after mathematical operations that could cause them.
I'm talking about the G++ compiler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C99/C++11 具有浮点控制函数(例如
fetestexcept
)和定义的标志(包括FE_UNDERFLOW
),可以让您合理地可移植地检测浮点下溢(即,使用任何支持这些的编译器/库)。虽然它们不那么可移植,但 gcc 有一个可以让您设置捕获的浮点异常的
feenableexcept
。当您启用的异常之一触发时,您的程序将收到SIGFPE
信号。至少在大多数硬件上,没有等效的整数运算——下溢仅产生 2 的补码(或其他)结果,并(例如)设置标志(例如,进位和符号位)以表明发生了什么。 C99/C++11 确实有一些针对整数溢出之类的标志,但我不认为它们得到了广泛的支持。
C99/C++11 have floating point control functions (e.g.
fetestexcept
) and defined flags (includingFE_UNDERFLOW
) that should let you detect floating point underflow reasonably portably (i.e., with any compiler/library that supports these).Though they're not as portable, gcc has an
feenableexcept
that will let you set floating point exceptions that are trapped. When one of the exceptions you've enabled fires, your program will receive aSIGFPE
signal.At least on most hardware, there's no equivalent for integer operations -- an underflow simply produces a 2's complement (or whatever) result and (for example) sets the the flags (e.g., carry and sign bits) to signal what happened. C99/C++11 do have some flags for things like integer overflow, but I don't believe they're nearly as widely supported.