<分区>
Possible Duplicate:
Best way to detect integer overflow in C/C++
当我在 C++ 中使用大量数字编写代码时,我常常无法判断何时发生溢出,即使我使用的是 long long 或其他 64 位数据类型。有没有比观察错误值更有效的方法来检测何时发生溢出?
<分区>
Possible Duplicate:
Best way to detect integer overflow in C/C++
当我在 C++ 中使用大量数字编写代码时,我常常无法判断何时发生溢出,即使我使用的是 long long 或其他 64 位数据类型。有没有比观察错误值更有效的方法来检测何时发生溢出?
最佳答案
您从标准 C++ 中获得的可能不多:
5 Expressions
4 If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]
您最好的选择是使用 <cstdint>
中定义的标准固定宽度整数类型例如 uint32_t
.
看看 <cerrno>
标题也是错误代码,例如 EOVERFLOW
.然后是overflow_error
/underflow_error
来自 <stdexcept>
的类(class).
关于c++ - C++中的自动溢出检测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865443/