Simple method to detect int overflow To detect int overflow/underflow in C, I use this code. What might be a simpler and more portable way of coding this (that is, fewer conditions)?

Assume 2's complement and don't use wider integers.

int a,b,sum;
sum = a + b;
// out-of-range only possible when the signs are the same.
if ((a &lt; 0) == (b &lt; 0)) {
  if (a &lt; 0) {
    // Underflow here means the result is excessively negative.
    if (sum &gt; b) UnderflowDetected();
  }
  else {
    if (sum &lt; b) OverflowDetected();  
  }
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.