<分区>
我有一个 sum()
函数。
我需要捕获所有溢出。
我搜索了网站,但没有找到这样做的好方法。
那么……有什么想法吗?
<分区>
我有一个 sum()
函数。
我需要捕获所有溢出。
我搜索了网站,但没有找到这样做的好方法。
那么……有什么想法吗?
最佳答案
正如其他人所说,如果结果与两个操作数的符号不同,则发生二进制补码溢出。
反之亦然。除非操作数具有相同的符号(负数或非负数)并且结果相反,否则不会发生二进制补码溢出。
不过,就个人而言,我更喜欢更直接的方法:
int_type a = 12356, b = 98765432;
if ( b > 0 && a > std::numeric_limits< int_type >::max() - b )
throw std::range_error( "adding a and b would cause overflow" );
if ( b < 0 && a < std::numeric_limits< int_type >::min() - b )
throw std::range_error( "adding a and b would cause underflow" );
int_type c = a + b;
这将捕获有符号和无符号的溢出/下溢,并且更容易看到发生了什么。
此外,C++ 中的整数有符号溢出不能保证环绕,因为不需要二进制补码算法。有符号整数溢出甚至会崩溃,尽管这种情况不太可能发生。所以就语言而言,最好在溢出发生之前停止它。 C++03 §5/5:
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, unless such an expression is a constant expression (5.19), in which case the program is ill-formed. [Note: most existing implementations of C++ ignore integer overflows. …]
另见 Boost Numeric Conversion库,尽管我不确定它是否可以解决 std::numeric_limits
无法解决的问题。
关于c++ - 如何在 C++ 中捕获整数溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7451207/