Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor edits

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
bgColor#FFCCCC
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
bgColor#ccccff

public static final int MASK = 1337;
public static final int OFFSET = -1337;

public static int computeCode(int x) {
  return (x & MASK) + OFFSET;
}

...