title: Integer division overflows
body: <h2>The Problem</h2>
  
  <p>I have been thinking about integer (type int) overflows, and it occurs to me that division could overflow.</p>
  
  <p><strong>Example</strong>: On my current platform, I have</p>
  
  <pre><code>INT_MIN == -INT_MAX - 1
  </code></pre>
  
  <p>and thus</p>
  
  <pre><code>INT_MIN &lt; -INT_MAX
  </code></pre>
  
  <p>and thus</p>
  
  <pre><code>INT_MIN / -1 &gt; -INT_MAX / -1
  </code></pre>
  
  <p>and thus</p>
  
  <pre><code>INT_MIN / -1 &gt; INT_MAX.
  </code></pre>
  
  <p>Hence, the division ( INT_MIN / -1 ) does overflow.</p>
  
  <hr>
  
  <h2>The Questions</h2>
  
  <p>So, I have two questions:</p>
  
  <ol>
  <li><p>What (cross-platform) C code could one write in order to prevent division overflows (for type (signed) int)?</p></li>
  <li><p>What guarantees (in C or C++ standard) might help to devise the code?</p></li>
  </ol>
  
  <hr>
  
  <p>For example, if the standard guarantees that we have either</p>
  
  <pre><code>INT_MIN == -INT_MAX - 1
  </code></pre>
  
  <p>or</p>
  
  <pre><code>INT_MIN == -INT_MAX,
  </code></pre>
  
  <p>then the following code appears to prevent overflows.</p>
  
  <pre><code>#include &lt;limits.h&gt;
  
  /*
        Try to divide integer op1 by op2.
        Return
          0 (success) or
          1 (possibly overflow prevented).
        In case of success, write the quotient to res.
  */
  
  int safe_int_div(int * res, int op1, int op2) {
  
    /*   assert(res != NULL);   */
    /*   assert(op2 != 0);      */
  
    if ( op1 == INT_MIN &amp;&amp; op2 == -1 )  {
      return 1;
    }
    *res = op1 / op2;
    return 0;
  }
  </code></pre>