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

后端 未结 10 1213
温柔的废话
温柔的废话 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 10:53

    You can see here the operator precedence in Java: http://bmanolov.free.fr/javaoperators.php . Because + and - have the same precedence, they will be executed in the order in which they appear.

    If you want to be more clear about what which operation takes place first (or if you want to break the built-in precedence), you can (and should) use parantheses (( and )), like this:

    x = (a - b) + (c * (d - e))

    0 讨论(0)
  • 2021-01-04 10:55

    It seems to me there will always be a side effect from executing X + q - 1 When you should be executing X - 1 + q.

    When the sum x + q exceeds Bignum by 1, the left to right execution will succeed... The out of order execution will generate an overflow.

    So the out of order execution has a side-effect.

    Unless the out-of-order execution traps that overflow itself, then re-do es the calculation in the correct order when necessary to avoid the side effect.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 11:00

    Important to add here is that java does have in line precedence for operators which appears to be based on the basic arithmetic order of operations. For a list of full precedence look at this source

    0 讨论(0)
提交回复
热议问题