title: Overflow occurs, but errno is not ERANGE. How does this happen?
body: <p>I'm trying to make use of <code>errno</code> to detect if I've performed an operation that causes overflow. However, although I've written a function which deliberately overflows, <code>errno == ERANGE</code> is false. What's going on here?</p>
  
  <p>Here's the code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;errno.h&gt;
  
  int main(int argc, char* argv[]) {
      unsigned char c = 0;
      int i;
  
      for (i = 0; i&lt; 300; i++) {
          errno = 0;
          c = c + 1;
          if (errno == ERANGE) {// we have a range error
              printf("Overflow. c = %u\n", c);
          } else {
              printf("No error. c = %u\n", c);
          }
      }
      return 0;
  }
  </code></pre>
  
  <p>I expected this to give an overflow error at the point where we added one to 255, but there is no error. Here's the (truncated) output:</p>
  
  <pre><code>No error. c = 245
  No error. c = 246
  No error. c = 247
  No error. c = 248
  No error. c = 249
  No error. c = 250
  No error. c = 251
  No error. c = 252
  No error. c = 253
  No error. c = 254
  No error. c = 255
  No error. c = 0
  No error. c = 1
  No error. c = 2
  No error. c = 3
  No error. c = 4
  No error. c = 5
  No error. c = 6
  No error. c = 7
  No error. c = 8
  No error. c = 9
  </code></pre>
  
  <p>Can someone explain why it doesn't detect the error, and how I might change it or otherwise make a function that can detect if my value has overflowed? Note: ultimately I want to be doing this with <code>long int</code>s, so it's not possible to simply convert it to a larger data type.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I've since found some simple functions to detect overflow from addition and multiplication of integral data types, respectively. It doesn't cover all situations, but it covers a lot of them.</p>
  
  <p>Multiplication:</p>
  
  <pre><code>int multOK(long x, long y)
  /* Returns 1 if x and y can multiply without overflow, 0 otherwise */
  {
      long p = x*y;
  
      return !x || p/x == y;
  }
  </code></pre>
  
  <p>Signed addition:</p>
  
  <pre><code>int addOK(long x, long y)
  /* Returns 1 if x and y can add without overflow, 0 otherwise */
  {
      long sum = x+y;
      int neg_over = (x &lt; 0) &amp;&amp; (y &lt; 0) &amp;&amp; (sum &gt;= 0);
      int pos_over = (x &gt;= 0) &amp;&amp; (y &gt;= 0) &amp;&amp; (sum &lt; 0);
      return !neg_over &amp;&amp; !pos_over;
  }
  </code></pre>
  
  <p>Unsigned addition:</p>
  
  <pre><code>int unsignedAddOK(unsigned long x, unsigned long y)
  /* Returns 1 if x and y can add without overflow, 0 otherwise */
  {
      unsigned long sum = x+y;
  
      return sum &gt; x &amp;&amp; sum &gt; y;
  }
  </code></pre>