CodeQL documentation

Implicit narrowing conversion in compound assignment

ID: java/implicit-cast-in-compound-assignment
Kind: problem
Security severity: 8.1
Severity: warning
Precision: very-high
Tags:
   - reliability
   - security
   - external/cwe/cwe-190
   - external/cwe/cwe-192
   - external/cwe/cwe-197
   - external/cwe/cwe-681
Query suites:
   - java-code-scanning.qls
   - java-security-extended.qls
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Compound assignment statements of the form x += y or x *= y perform an implicit narrowing conversion if the type of x is narrower than the type of y. For example, x += y is equivalent to x = (T)(x + y), where T is the type of x. This can result in information loss and numeric errors such as overflows.

Recommendation

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.

Example

If x is of type short and y is of type int, the expression x + y is of type int. However, the expression x += y is equivalent to x = (short) (x + y). The expression x + y is cast to the type of the left-hand side of the assignment: short, possibly leading to information loss.

To avoid implicitly narrowing the type of x + y, change the type of x to int. Then the types of x and x + y are both int and there is no need for an implicit cast.

References

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy