title: C++ overflow detection for large numbers (unsigned long long)
body: <p>I am dealing with large integers (unsigned long long) and need to guard for overflow conditions. The code throws the exception regardless if there actually is one:</p>
  
  <pre><code>try
  {
      unsigned long long y = std::numeric_limits&lt;unsigned long long&gt;::max() - 2;
      unsigned long long z = 1;
      int size = - 1;
      if((y+z) ^ y &lt; 0) //If y+z causes overflow its sign will be changed =&gt; y and (y+z) will have opposite signs
          throw std::overflow_error("overflow of y+z");
      //int* myarray= new int[size]; VS Debug Library catches it earlier than catch()
      printf("%d\n", y*(y+z));
  }
  catch(exception&amp; e)
  {
      cout &lt;&lt; e.what() &lt;&lt; endl;
  }
  </code></pre>
  
  <p>Since it is of the largest data type(64 bits) already, there is no room to promote to anything larger.</p>
  
  <p>New code:</p>
  
  <pre><code>try
  {
      unsigned long long int y = std::numeric_limits&lt;unsigned long long int&gt;::max() - 2;
      unsigned long long int z = std::numeric_limits&lt;unsigned long long int&gt;::max() / 2;
      unsigned long long delta = std::numeric_limits&lt;unsigned long long int&gt;::max() - y;
      int size = - 1;
      if(z &gt; delta) //If y+z causes overflow its sign will be changed =&gt; y and (y+z) will have opposite signs
          throw std::overflow_error("overflow of y+z");
      //int* myarray= new int[size]; VS Debug Library catches it earlier than catch()
      printf("%d\n", (y+z));
  }
  catch(exception&amp; e)
  {
      cout &lt;&lt; e.what() &lt;&lt; endl;
  }
  </code></pre>