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.
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?
Overflow Detection – So overflow can be detected by checking Most Significant Bit(MSB) of two operands and answer. But Instead of using 3-bit Comparator Overflow can also be detected using 2 Bit Comparator just by checking Carry-in(C-in) and Carry-Out(C-out) from MSB's. Consider N-Bit Addition of 2's Complement number.
The rules for detecting overflow in a two's complement sum are simple: If the sum of two positive numbers yields a negative result, the sum has overflowed. If the sum of two negative numbers yields a positive result, the sum has overflowed. Otherwise, the sum has not overflowed.
When two unsigned numbers are added an overflow is detected from the end carry out of the most significant position.
Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1.
You could use
if((a + b) < a)
The point is that if a + b
is overflowing, the result will be trimmed and must be lower then a
.
Consider the case with hypothetical bound range of 0 -> 9 (overflows at 10):
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With