Is the left-to-right order of operations guaranteed in Java?

后端 未结 10 1331
温柔的废话
温柔的废话 2021-01-04 10:16

Consider this function:

public static final int F(int a, int b) {
    a = a - 1 + b;
    // and some stuff
    return a;
}

Is it required

10条回答
  •  没有蜡笔的小新
    2021-01-04 11:00

    Yes, it's in the Java language specification, §15.7.

    The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

    It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.

提交回复
热议问题