我有一个小疑问,为什么下面的代码输出i=2。
int i=2;
i=i++;
System.out.println(i);
有人能解释一下第2行发生了什么吗?
所以在这里做++没有意义吗?
谢谢
int i=2;
i=i++;
System.out.println(i);
有人能解释一下第2行发生了什么吗?
所以在这里做++没有意义吗?
谢谢
i=i++;
因为首先进行赋值操作,然后再执行递增操作。
类似于:
首先 i 被赋值为 2,然后执行 ++ 操作,但结果不会重新赋值给 i,所以 i 的值仍然是 2。
i = i++;
首先计算 i++
表达式,它会将 i
加一并返回加一前的值。由于你立即将这个值赋给了 i
,它重置了 i
的值,使得增量似乎从未发生过。i = ++i;
则会导致另一种行为。
感谢大家在我理解有价值的事情方面给予的帮助。
我在某处发现了一个不错的帖子。
我只是从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
这有助于我更好地理解。
如果我的观点有误,请添加。
感谢您所有的回答。
i++
值再次赋值给i
。int i = 2; i++; System.out.println(i);
- Roddy of the Frozen Peasint i = 2; System.out.println(++i);
- Marko Topolnik