<!DOCTYPE qhelp PUBLIC
  "-//Semmle//qhelp//EN"
  "qhelp.dtd">
<qhelp>
  <overview>
    <p>
      Checking for overflow of integer addition needs to be done with
      care, because automatic type promotion can prevent the check
      from working correctly.
    </p>
  </overview>
  <recommendation>
    <p>
      Use an explicit cast to make sure that the result of the addition is
      not implicitly converted to a larger type.
    </p>
  </recommendation>
  <example>
    <sample src="BadAdditionOverflowCheckExample1.cpp" />
    <p>
      On a typical architecture where <tt>short</tt> is 16 bits
      and <tt>int</tt> is 32 bits, the operands of the addition are
      automatically promoted to <tt>int</tt>, so it cannot overflow
      and the result of the comparison is always false.
    </p>
    <p>
      The code below implements the check correctly, by using an
      explicit cast to make sure that the result of the addition
      is <tt>unsigned short</tt>.
    </p>
    <sample src="BadAdditionOverflowCheckExample2.cpp" />
  </example>
  <references>
    <li><a href="http://c-faq.com/expr/preservingrules.html">Preserving Rules</a></li>
    <li><a href="https://www.securecoding.cert.org/confluence/plugins/servlet/mobile#content/view/20086942">Understand integer conversion rules</a></li>
  </references>
</qhelp>
