@@ -22,33 +22,35 @@ In the following example, even though <code>delta</code> has been declared
2222<code >unsigned short</code >, C/C++ type promotion rules require that its
2323type is promoted to the larger type used in the addition and comparison,
2424namely a <code >signed int</code >. As a result, the entire expression is
25- evaluated using <code >signed</code > values and its value is therefore undefined.
25+ evaluated using <code >signed</code > integers and may overflow, and hence
26+ is undefined.
2627</p >
2728<sample src =" SignedOverflowCheck-bad1.cpp" />
2829<p >
2930In the following example, even though both <code >n</code > and <code >delta</code >
30- have been declared <code >unsigned short</code >, C/C++ type promotion rules
31- require that both parameters be promoted to the next bigger <code >signed</code >
32- integer type (in this case <code >signed int</code >) before being added together.
33- As a result, the entire expression is evaluated using <code >signed</code > values
34- and its value is therefore undefined. (Note, however, that the addition cannot
35- overflow since we are adding two "small" <code >unsigned short</code > values.)
31+ have been declared <code >unsigned short</code >, both are promoted to
32+ <code >signed int</code > prior to addition. Because we started out with the
33+ narrower <code >short</code > type, the addition is guaranteed not to overflow
34+ and is therefore defined. But the fact that <code >n1 + delta</code > never
35+ overflows means that the condition <code >n1 + delta < n1</code > will never
36+ hold true, which likely is not what the programmer intended. (see also the
37+ <code >BadArithmeticOverflow.Check.ql</code > query).
3638</p >
3739<sample src =" SignedOverflowCheck-bad2.cpp" />
3840<p >
3941The following example builds upon the previous one. Again, we have two
4042<code >unsigned short</code > values getting promoted to a wider type. However,
4143since <code >delta</code > is explicitly cast to an <code >unsigned</code > type,
4244<code >n1</code > (on both sides of the comparison) is promoted to
43- <code >unsigned</code > as well. Since we are now operating on
45+ <code >unsigned int </code > as well. Since we are now operating on
4446<code >unsigned</code > values, the overflow check is defined and supported by
4547standard C/C++.
4648</p >
4749<sample src =" SignedOverflowCheck-good1.cpp" />
4850<p >
4951In the next example, a value of type <code >signed int</code > is
5052added to a value of type <code >unsigned int</code >. Because
51- the types are of the same size, C/C++ promotion rules dictate that
53+ the types are of the same size, C/C++ conversion rules dictate that
5254<code >unsigned int</code > is chosen as the overall type of the addition
5355operation. The entire expression is evaluated using <code >unsigned</code >
5456values, which is allowed and defined behavior per the C/C++ standard.
0 commit comments