Simple method to detect int overflow
It's not possible to avoid undefined behaviour by testing for it after the fact! If the addition overflows then there is already undefined behaviour here:

sum = a + b;


so attempting to test afterwards is too late. You have to test for possible overflow before you do a signed addition. (If you're puzzled by this, read Dietz et al. (2012), "Understanding Integer Overﬂow in C/C++". Or even you're not puzzled: it's an excellent paper!)

If it were me, I'd do something like this:

#include &lt;limits.h&gt;

int safe_add(int a, int b) {
    if (a &gt; 0 &amp;&amp; b &gt; INT_MAX - a) {
        /* handle overflow */
    } else if (a &lt; 0 &amp;&amp; b &lt; INT_MIN - a) {
        /* handle underflow */
    }
    return a + b;
}


but I'm not entirely sure what the point of having separate cases for overflow and underflow is.

I also use Clang's -fsanitize=undefined when building for test.