考虑这个函数:
public static final int F(int a, int b) {
a = a - 1 + b;
// and some stuff
return a;
}
JVM 的实现是否需要在 + b
之前执行 - 1
?
如果我们有一个附加到 JVM 的系统分析器,我们会看到 + b
操作在 + 1
操作之前执行吗?
最佳答案
实际上,我不同意其余的答案。人们所指的 JLS §15.7 讨论了操作数的评估。也就是说,在表达式中
x = foo() - 1 + bar()
,调用方法的顺序。
相关部分是§15.7.3,其中规定
An implementation may not take advantage of algebraic identities such as the associative law to rewrite expressions into a more convenient computational order unless it can be proven that the replacement expression is equivalent in value and in its observable side effects [...]
由于表达式 x = x - 1 + q
在所有方面都等同于 x = x + q - 1
,允许符合规范的实现重写表达式(如果它出于某种原因应该决定效率更高)。
关于java - Java 中是否保证从左到右的操作顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9081393/