C - 检测加法的无符号整数溢出 [英] C - detect unsigned int overflow of addition
问题描述
这是我在尝试将两个数字相加时检测是否发生无符号整数溢出的实现.
This is my implementation to detect if an unsigned int overflow has occurred when trying to add two numbers.
我的系统上 unsigned int (UINT_MAX) 的最大值是 4294967295.
The max value of unsigned int (UINT_MAX) on my system is 4294967295.
int check_addition_overflow(unsigned int a, unsigned int b) {
if (a > 0 && b > (UINT_MAX - a)) {
printf("overflow has occured\n");
}
return 0;
}
这似乎适用于我尝试过的值.
This seems to work with the values I've tried.
任何流氓案件?你认为有什么好处和坏处?
Any rogue cases? What do you think are the pros and cons?
推荐答案
你可以使用
if((a + b) < a)
重点是如果a + b
溢出,结果将被修剪并且必须低于a
.
The point is that if a + b
is overflowing, the result will be trimmed and must be lower then a
.
考虑假设边界范围为 0 -> 9(在 10 处溢出)的情况:
Consider the case with hypothetical bound range of 0 -> 9 (overflows at 10):
b
最多可以是 9.对于任何值 a
使得 a + b >= 10
,(a + 9) % 10 <一个
.
对于任何值 a
, b
使得 a + b <;10
,由于b
不是负数,a + b >= a
.
b
can be 9 at the most. For any value a
such that a + b >= 10
, (a + 9) % 10 < a
.
For any values a
, b
such that a + b < 10
, since b
is not negative, a + b >= a
.
这篇关于C - 检测加法的无符号整数溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!