@@ -24,25 +24,36 @@ type 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
2525evaluated using <code >signed</code > values and its value is therefore undefined.
2626</p >
27- <sample src =" SignedOverflowCheck-bad .cpp" />
27+ <sample src =" SignedOverflowCheck-bad1 .cpp" />
2828<p >
2929In the following example, even though both <code >n</code > and <code >delta</code >
3030have been declared <code >unsigned short</code >, C/C++ type promotion rules
3131require 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- so as to avoid overflows or underflows. As a result, the entire expression is
34- evaluated using <code >signed</code > values and its value is therefore undefined.
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.)
3536</p >
3637<sample src =" SignedOverflowCheck-bad2.cpp" />
3738<p >
39+ The following example builds upon the previous one. Again, we have two
40+ <code >unsigned short</code > values getting promoted to a wider type. However,
41+ since <code >delta</code > is explicitly cast to an <code >unsigned</code > type,
42+ <code >n1</code > (on both sides of the comparison) is promoted to
43+ <code >unsigned</code > as well. Since we are now operating on
44+ <code >unsigned</code > values, the overflow check is defined and supported by
45+ standard C/C++.
46+ </p >
47+ <sample src =" SignedOverflowCheck-good1.cpp" />
48+ <p >
3849In the next example, a value of type <code >signed int</code > is
3950added to a value of type <code >unsigned int</code >. Because
4051the types are of the same size, C/C++ promotion rules dictate that
4152<code >unsigned int</code > is chosen as the overall type of the addition
4253operation. The entire expression is evaluated using <code >unsigned</code >
4354values, which is allowed and defined behavior per the C/C++ standard.
4455</p >
45- <sample src =" SignedOverflowCheck-good .cpp" />
56+ <sample src =" SignedOverflowCheck-good2 .cpp" />
4657</example >
4758<references >
4859<li ><a href =" http://c-faq.com/expr/preservingrules.html" >comp.lang.c FAQ list · Question 3.19 (Preserving rules)</a ></li >
0 commit comments