Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As others have said, if the result is a different sign than both operands, two's complement signed overflow occurred.</p> <p>The converse is also true. Two's complement signed overflow cannot occur unless the operands are the same sign (negative or non-negative) and the result is the opposite.</p> <p>Still, personally, I prefer a more straightforward approach:</p> <pre><code>int_type a = 12356, b = 98765432; if ( b &gt; 0 &amp;&amp; a &gt; std::numeric_limits&lt; int_type &gt;::max() - b ) throw std::range_error( "adding a and b would cause overflow" ); if ( b &lt; 0 &amp;&amp; a &lt; std::numeric_limits&lt; int_type &gt;::min() - b ) throw std::range_error( "adding a and b would cause underflow" ); int_type c = a + b; </code></pre> <p>This will catch both signed and unsigned overflow/underflow, and it is much easier to see what is happening.</p> <p>Moreover, integral signed overflow in C++ is not guaranteed to wrap around, since two's complement arithmetic is not required. Signed integer overflow can even crash, although it is unlikely. So in terms of the language, it's best to stop overflow <em>before</em> it occurs. C++03 §5/5:</p> <blockquote> <p>If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined, unless such an expression is a constant expression (5.19), in which case the program is ill-formed. [Note: most existing implementations of C++ ignore integer overflows. …]</p> </blockquote> <p>See also the <a href="http://www.boost.org/doc/libs/1_47_0/libs/numeric/conversion/doc/html/index.html" rel="nofollow noreferrer">Boost Numeric Conversion</a> library, although I'm not sure it can do anything for this problem that <code>std::numeric_limits</code> can't.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload