[zlaski/bad-addition-qhelp-reword] Initial change.

This commit is contained in:
Ziemowit Laski
2019-10-22 13:43:35 -07:00
parent 219fcb7889
commit ad4cd6f2bb
2 changed files with 9 additions and 6 deletions

View File

@@ -6,7 +6,8 @@
<p>
Checking for overflow of integer addition needs to be done with
care, because automatic type promotion can prevent the check
from working correctly.
from working as intended, with the same value (<code>true</code>
or <code>false</code>) always being returned.
</p>
</overview>
<recommendation>
@@ -18,15 +19,16 @@
<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
On a typical architecture where <code>short</code> is 16 bits
and <code>int</code> is 32 bits, the operands of the addition are
automatically promoted to <code>int</code>, 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>.
is <code>unsigned short</code> (which may overflow, in which case
the comparison would evaluate to <code>true</code>).
</p>
<sample src="BadAdditionOverflowCheckExample2.cpp" />
</example>

View File

@@ -1,3 +1,4 @@
bool checkOverflow(unsigned short x, unsigned short y) {
return (x + y < x); // BAD: x and y are automatically promoted to int.
// BAD: comparison is always false due to type promotion
return (x + y < x);
}