是否有保证执行以下 java 代码的顺序:
int i = getA() + getB();
getA()
是否总是在 getB()
之前执行,正如任何普通人所期望的那样?
最佳答案
是的,是的。来自 JLS,第 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.
...
The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
还有:
The Java programming language also guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.
关于java - java中的序列点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4352954/