Java中保证了从左到右的操作顺序吗? [英] Is the left-to-right order of operations guaranteed in Java?
问题描述
考虑这个函数:
public static final int F(int a, int b) {
a = a - 1 + b;
// and some stuff
return a;
}
JVM的实现是否需要执行 - 1
之前 + b
?
Is it required for implementations of JVMs to execute - 1
before + b
?
如果我们有一个连接到JVM的系统探查器,我们会在 + 1
操作之前看到 + b
操作吗?
If we have a system profiler attached to the JVM, will we see the + b
operation being carried out before the + 1
operation?
推荐答案
实际上,我不同意其余的答案。人们所指的JLS§15.7讨论了操作数的评估。也就是说,在表达式中
Actually, I will disagree with the rest of the answers. The JLS §15.7 that people are referring to discusses the evaluation of operands. That is, in the expression
x = foo() - 1 + bar()
,调用方法的顺序。
相关部分是§ 15.7.3,指定
The relevant section is §15.7.3, which specifies
实施可能利用代数身份,例如关联法则将表达式重写为更方便的计算顺序除非可以证明替换表达式等价值及其可观察的副作用 [...]
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
,允许符合条件的实现重写表达式(如果由于某种原因应该决定更有效)。
Since the expression x = x - 1 + q
is equivalent in all ways to x = x + q - 1
, a conforming implementation is allowed to rewrite the expression (if it for some reason should decide that is more efficient).
这篇关于Java中保证了从左到右的操作顺序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!