sequence points in java

早过忘川 提交于 2019-11-30 17:38:01

问题


Is there a guaranteed sequence of execution of the following java code:

int i = getA() + getB();

Is getA() always executed before getB(), as any average person would expect?


回答1:


Yes, it is. From the JLS, section 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.

and also:

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.



来源:https://stackoverflow.com/questions/4352954/sequence-points-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!