如何检查是否发生溢出? [英] How to check if overflow occured?
问题描述
可能重复:
检测C/C ++中整数溢出的最佳方法 >
Possible Duplicate:
Best way to detect integer overflow in C/C++
这可能是一个菜鸟问题,但是如何检查某些溢出影响了C中我的数字的值.例如,在将整数相乘并等待整数结果时,如果实际结果大于max-integer值,实际结果已更改(对吗?).那么,如何判断是否发生了这种情况?
This is probably a rookie question, but how can I check some overflow affected the value of my numbers in C. For example, when multiplying integers, and waiting for an integer result, if actual result was bigger than max-integer value, actual result is altered(right?). So how can I tell if something like this occured?
推荐答案
带符号的整数溢出就像被零除-导致未定义的行为,因此您必须在执行前检查它们是否会出现.潜在溢出的操作.一旦溢出,所有赌注都将消失-您的代码可以执行任何操作.
Signed integer overflow is like division by zero - it leads to undefined behaviour, so you have to check if it would occur before executing the potentially-overflowing operation. Once you've overflowed, all bets are off - your code could do anything.
在<limits.h>
中定义的*_MAX
和_MIN
宏可以派上用场,但是您需要注意不要在测试本身中调用未定义的行为.例如,要检查在给定的int a, b;
下a * b
是否会溢出,可以使用:
The *_MAX
and _MIN
macros defined in <limits.h>
come in handy for this, but you need to be careful not to invoke undefined behaviour in the tests themselves. For example, to check if a * b
will overflow given int a, b;
, you can use:
if ((b > 0 && a <= INT_MAX / b && a >= INT_MIN / b) ||
(b == 0) ||
(b == -1 && a >= -INT_MAX) ||
(b < -1 && a >= INT_MAX / b && a <= INT_MIN / b))
{
result = a * b;
}
else
{
/* calculation would overflow */
}
(请注意,这避免了一个细微的陷阱,即您无法计算INT_MIN / -1
-这样的数字不能保证可表示,并且确实会导致常见平台上的致命陷阱.)
(Note that one subtle pitfall this avoids is that you can't calculate INT_MIN / -1
- such a number isn't guaranteed to be representable and indeed causes a fatal trap on common platforms).
这篇关于如何检查是否发生溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!