int i,j,k; i = j = k = 3; i = k++;
所以对我而言,变量’i’现在必须具有值4,因为我们将’k’的增量分配给它似乎是合乎逻辑的.在多项选择测试中,第三行之后的正确值代替:
k = 4
和
i != 4
由于我们将k的增量分配给i,所以给定的解决方案与我预期的完全相反.
提前致谢!
解决方法
我不会回答这个问题,但所有答案(在发布时)都犯同样的错误:这不是时间问题;这是表达式k的值的问题.
对i的分配发生在k的增量之后,但是表达式k的值是k的原始值,而不是递增的值.
所以这段代码:
i = k++;
相当于:
int tmp = k; k++; i = tmp;
从section 15.14.2 of the JLS(重点):
[…] Otherwise,the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition,binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary,the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to Boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.
这个差异是非常重要的,可以很容易地看出,如果不使用postfix表达式作为一个赋值,你调用一个方法:
public class Test { private static int k = 0; public static void main(String[] args) throws Exception { foo(k++); } private static void foo(int x) { System.out.println("Value of parameter: " + x); System.out.println("Value of k: " + k); } }
结果是:
Value of parameter: 0 Value of k: 1