Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test whether sum of two integers might overflow

Tags:

c

From C traps and pitfalls

If a and b are two integer variables, known to be non-negative then to test whether a+b might overflow use:

     if ((int) ((unsigned) a + (unsigned) b) < 0 )
        complain();

I didn't get that how comparing the sum of both integers with zero will let you know that there is an overflow?

like image 742
Chankey Pathak Avatar asked Aug 07 '11 04:08

Chankey Pathak


People also ask

How do you know if an addition will overflow?

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. The solution of casting to long and adding to find detecting the overflow is not allowed.

How do you check for overflow conditions?

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.

How do you overflow integers?

An integer overflow or wraparound happens when an attempt is made to store a value that is too large for an integer type. The range of values that can be stored in an integer type is better represented as a circular number line that wraps around.


1 Answers

The code you saw for testing for overflow is just bogus.

For signed integers, you must test like this:

if (a^b < 0) overflow=0; /* opposite signs can't overflow */
else if (a>0) overflow=(b>INT_MAX-a);
else overflow=(b<INT_MIN-a);

Note that the cases can be simplified a lot if one of the two numbers is a constant.

For unsigned integers, you can test like this:

overflow = (a+b<a);

This is possible because unsigned arithmetic is defined to wrap, unlike signed arithmetic which invokes undefined behavior on overflow.

like image 124
R.. GitHub STOP HELPING ICE Avatar answered Sep 21 '22 19:09

R.. GitHub STOP HELPING ICE