-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathInformationLoss.qhelp
More file actions
51 lines (39 loc) · 2.01 KB
/
InformationLoss.qhelp
File metadata and controls
51 lines (39 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>Compound assignment statements of the form <code>x += y</code> or
<code>x *= y</code> perform an implicit narrowing conversion
if the type of <code>x</code> is narrower than the type of <code>y</code>.
For example, <code>x += y</code> is equivalent to <code>x = (T)(x + y)</code>,
where <code>T</code> is the type of <code>x</code>.
This can result in information loss and numeric errors such as overflows.
</p>
</overview>
<recommendation>
<p>Ensure that the type of the left-hand side of the compound assignment statement
is at least as wide as the type of the right-hand side.</p>
</recommendation>
<example>
<p>If <code>x</code> is of type <code>short</code> and <code>y</code> is of type <code>int</code>,
the expression <code>x + y</code> is of type <code>int</code>. However, the expression <code>x += y</code>
is equivalent to <code>x = (short) (x + y)</code>. The expression <code>x + y</code> is cast to the type of
the left-hand side of the assignment: <code>short</code>, possibly leading to information loss.</p>
<p>To avoid implicitly narrowing the type of <code>x + y</code>, change the type of <code>x</code> to
<code>int</code>. Then the types of <code>x</code> and <code>x + y</code> are both <code>int</code> and there is no
need for an implicit cast.</p>
</example>
<references>
<li>
J. Bloch and N. Gafter, <em>Java Puzzlers: Traps, Pitfalls, and Corner Cases</em>, Puzzle 9. Addison-Wesley, 2005.
</li>
<li>
The Java Language Specification:
<a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2">Compound Assignment Operators</a>,
<a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3">Narrowing Primitive Conversion</a>.
</li>
<li>The CERT Oracle Secure Coding Standard for Java:
<a href="https://www.securecoding.cert.org/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow">NUM00-J. Detect or prevent integer overflow</a>.</li>
</references>
</qhelp>