This is my implementation to detect if an unsigned int overflow has occurred when trying to add two numbers.
The max value of unsigned int (UINT_MAX) on my system is 4294967295.
void check_addition_overflow(unsigned int a, unsigned int b) {
if (b > (UINT_MAX - a)) {
printf("overflow has occured\n");
}
}
This seems to work with the values I've tried.
Any rogue cases? What do you think are the pros and cons?
Best Answer
You could use
The point is that if
a + b
is overflowing, the result will be trimmed and must be lower thena
.Consider the case with hypothetical bound range of 0 -> 9 (overflows at 10):
b
can be 9 at the most. For any valuea
such thata + b >= 10
,(a + 9) % 10 < a
.For any values
a
,b
such thata + b < 10
, sinceb
is not negative,a + b >= a
.