Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

According to the Java Language Specification JLS, §15.7, "Evaluation Order":

...

§15.7.3, "Evaluation Respects Parentheses and Precedence" of the Java Language Specification adds:

Java programming language implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence.

When an expression contains side effects, these These two requirements can yield surprising resultsbe counterintuitive when expressions contain side effects. Evaluation of the operands proceeds left - to - right, without regard to operator precedence rules and indicative parentheses; evaluation of the operators, however, obeys precedence rules and parentheses.

Expressions must not write to memory that they subsequently read , and also must not write to any memory twice. Note that memory writing reads and reading writes can occur either directly in the expression from assignments or indirectly through side effects in methods called in the expression.

...

This noncompliant code example shows how side effects in expressions can lead to unanticipated outcomes. The programmer intends to write access control logic based on different threshold levels. Each user has a rating that must be above the threshold to be granted access. As shown, a simple method can calculate the rating. The get() method is expected to return a non-zero factor for users who are authorized , and a zero value for those who are unauthorized.

In this case, the programmer expects the rightmost subexpression to evaluate first because the * operator has a higher precedence than the + operator. The parentheses reinforce this belief. These ideas lead to the incorrect conclusion that the right-hand side evaluates to zero whenever the get() method returns zero. The programmer expects number to be assigned 0 because of the rightmost number = get() subexpression. Consequently, the test in the left-hand subexpression is expected to reject the unprivileged user because the rating value (number) is below the threshold of 10.

However, the program grants access to the unauthorized user because evaluation of the side-effect-infested subexpressions follows the left-to-right ordering rule.

Code Block
bgColor#FFcccc
class BadPrecedence {
  public static void main(String[] args) {
    int number = 17;
    int[] threshold = new int[20];
    threshold[0] = 10;
    number = (number > threshold[0]? 0 : -2) 
             + ((31 * ++number) * (number = get()));
    // ... 
    if (number == 0) {
      System.out.println("Access granted");
    } else {
      System.out.println("Denied access"); // number = -2
    }
  }
  public static int get() {
    int number = 0;
    // Assign number to non zero value if authorized else 0
    return number;
  }
}

...

This compliant solution uses equivalent code with no side effects . It performs only one write, to numberand performs not more than one write per expression. The resulting expression can be reordered without concern for the evaluation order of the component expressions, making the code easier to understand and maintain.

Code Block
bgColor#ccccff
int number = 17;

final int authnum = get();
number = ((31 * (number + 1)) * authnum) + (authnum > threshold[0]? 0 : -2);


Exceptions

EXP05-EX0: The increment and decrement operators (++ and --) read a numeric variable, and then assign a new value to the variable. These are well-understood and are an exception to this rule.EXP05-EX1: The logical operators || and && have well-understood short-circuit semantics, so expressions involving these operators do not may violate this rule. Consider the following code:

Code Block
bgColor#ccccff
public void exampleMethod(InputStream in) {
  int i;
  // Skip one char, process next
  while ((i = in.read()) != -1 && (i = in.read()) != -1) {
    // ...
  }

}

Although the overall conditional expression violates this rule, this code is compliant because the sub-expressions subexpressions on either side of the && operator do not violate it. Each subexpression has exactly one assignment and one side effect (the reading of a character from in).

...

Detection of all expressions involving both side effects and also multiple operator precedence levels is straightforward. Determining the correctness of such uses is infeasible in the general case; heuristic warnings could be useful.

...

CERT C Secure Coding Standard

EXP30-C. Do not depend on order of evaluation between sequence points

CERT C++ Secure Coding Standard

EXP30-CPP. Do not depend on order of evaluation between sequence points<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f04f00d2-dc42-44ca-b435-6bff0959c337"><ac:plain-text-body><![CDATA[

[ISO/IEC TR 24772:2010

http://www.aitcnet.org/isai/]

"Side?effects Side Effects and Order of Evaluation [SAM]" ]]></ac:plain-text-body></ac:structured-macro>

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="6d9c0b876dfad889-4efc8f01-415d4066-80ac95fa-384cdc7defd163c591c5540a"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[§15.7, " Evaluation Order"

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.7]

]]></ac:plain-text-body></ac:structured-macro>

 

§15.7.3, " Evaluation Respects Parentheses and Precedence"

...

EXP04-J. Ensure that autoboxed values have the intended type      02. Expressions (EXP)      EXP06-J. Do not use side-effecting expressions in assertions