问题描述
以下代码的输出是什么:
What is the output of the following code:
int x = 2;
x += x++ * x++ * x++;
System.out.println(x);
我知道 ++ variableName
是预先的-increment运算符和 variableName
的值在表达式中使用之前递增,而 variableName ++
在之后递增其值表达式被执行。我想知道的是 - 这个逻辑在这里是如何应用的?
I understand that ++variableName
is pre-increment operator and the value of variableName
is incremented before it is used in the expression whereas variableName++
increments its value after the expression is executed. What I want to know is - how does this logic apply here?
推荐答案
更容易看到x发生了什么= 1而不是2. x = 1
的输出为7.
Its easier to see the what is going on with x = 1 instead of 2. The output for x=1
is 7.
理解这一点的关键在JLS 表示在执行操作的任何部分之前完全评估每个操作数。
The key to the understanding of this is in JLS 15.7.2 which states that the every operand is fully evaluated before any part of the operation is performed.
因此,评估x ++(每次3次,从左到右,具有适当的优先级,这不是问题),然后评估操作*并将其分配给原始值。 / p>
Thus, x++ (each of 3 times, left to right with appropriate precedence which isn't an issue here) is evaluated, then the operation * is evaluated and assigned to the original value.
x = 1 + (1 * 2 * 3)
如果x以2开头,则得到:
If x starts out with 2, you get:
x = 2 + (2 * 3 * 4)
与C不同,它在Java中定义良好,并且在任何运行时的每次调用中都会表现相同。
Unlike in C, this is well defined in Java and will behave the same on each invocation in any runtime.
这篇关于如何在复杂表达式中计算java增量语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!