Java , C, and C++ programmers commonly make errors regarding the precedence rules of C 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 and, if not taken to excess, makes the code more readable.
This The Java Tutorials defines the precedence of operation by the order of the subclauses.
This recommendation is similar to EXP01-J, however it applies to more generally than expressions containing side effects.
...
The intent of the expression in this noncompliant code example is to add the variable OFFSET
with the result of the bitwise
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; } |
...
In this compliant solution, parentheses are used to ensure the expression evaluates as expected.
Code Block | ||
---|---|---|
| ||
public static final int MASK = 1337;
public static final int OFFSET = -1337;
public static int computeCode(int x) {
return (x & MASK) + OFFSET;
}
|
...