后增量行为
我有一点疑问。为什么下面的代码是打印值i = 2。
int i=2; i=i++; System.out.println(i);
有人可以解释一下第2行的情况。
所以这里做++没有意义吗?
谢谢
i=i++;
因为首先发生了赋值,所以增量适用。
就像是:
首先我得到2,然后++操作发生,但结果将不会重新分配给i,所以我的值将保持为2。
i = i++;
首先计算i++
表达式,它增加i
并在增量之前计算为i
的值。 由于您立即将此值赋给i
,它会重置i
的值,因此增量似乎从未发生过。 i = ++i;
会导致其他行为。
当你告诉i=i++;
你告诉计算机将i分配给i,然后增加i的值,但它不会影响i,因为我的值是2。
正确的方法应该是i=++i;
意思是,在将它分配给i之前加1,或者你可以简单地使用i++;
感谢所有人帮助我理解那些具有重要价值的东西。
我在这里发现了一些不错的post。
我从stackoverflow论坛给出的建议中得到了答案,但有一些明确的解释错过了我的感受。
Miljen Mikic建议链接不起作用并且说找不到页面。
以下问题的一些明确解释是
int a=2, b=2; int c = a++/b++; System.out.println(c);
拆解以下内容。
0:iconst_2 ; [I]Push the constant 2 on the stack[/I] 1:istore_1 ; [I]Pop the stack into local variable 1 (a)[/I] 2:iconst_2 ; [I]Push the constant 2 on the stack, again[/I] 3:istore_2 ; [I]Pop the stack into local variable 2 (b)[/I] 4:iload_1 ; [I]Push the value of a on the stack[/I] 5:iinc1, 1 ; [I]Add 1 to local variable 1 (a)[/I] 8:iload_2 ; [I]Push the value of b on the stack[/I] 9:iinc2, 1 ; [I]Add 1 to local variable 2 (b)[/I] 12:idiv ; [I]Pop two ints off the stack, divide, push result[/I] 13:istore_3 ; [I]Pop the stack into local variable 3 (c)[/I] 14:return
这有助于我更好地理解。
请加上这个如果我错了。
谢谢你的所有答案。