Java programmers commonly Programmers frequently make errors regarding the precedence rules of operators due to the unintuitive low-precedence levels of &
, |
, ^
, <<
, and >>
. Mistakes regarding precedence rules can be avoided by the suitable use of parentheses. Using parentheses defensively reduces errors andDefensive use of parentheses, if not taken to excess, makes the code more readablealso improves code readability.
The Java Tutorials defines the precedence of operation by the order of the subclauses.
...
The intent of the expression in this noncompliant code example is to add the variable OFFSET
with the result of the bitwise
and AND
between x
and MASK
.
Code Block | ||
---|---|---|
| ||
public static final int MASK = 1337;
public static final int OFFSET = -1337;
public static int computeCode(int x) {
return x & MASK + OFFSET;
}
|
Because of Due to operator precedence rules, the expression is parsed as:
Code Block | ||
---|---|---|
| ||
x & (MASK + OFFSET)
|
Which This gets evaluated as shown below, resulting in the value 0.
Code Block | ||
---|---|---|
| ||
x & (1337 - 1337)
|
...
Compliant Solution
In this compliant solution, parentheses are used to ensure that the expression evaluates as expected.
...
EXP00-EX1: Mathematical expressions that follow algebraic order do not require parentheses. For instance, in consider the expression:
Code Block |
---|
x + y * z |
the By mathematical convention, multiplication is performed before the addition by mathematical convention. Consequently, parentheses may prove to enforce this would be redundant in this case.
Code Block | ||
---|---|---|
| ||
x + (y * z)
|
Risk Assessment
...
This rule appears in the C++ Secure Coding Standard as EXP00-CPP. Use parentheses for precedence of operation.
References
Wiki Markup |
---|
\[[Tutorials 08|AA. Java References#Tutorials 08]\] [Expressions, Statements, and Blocks|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html] |