From C traps and pitfalls
If a and b are two integer variables, known to be non-negative then to
test whethera+bmight 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?
The code you saw for testing for overflow is just bogus.
For signed integers, you must test like this:
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:
This is possible because unsigned arithmetic is defined to wrap, unlike signed arithmetic which invokes undefined behavior on overflow.