** Dup:What's the difference between X = X++; vs X++;? **
所以,即使我知道你永远不会在代码中做到这一点,我仍然很好奇:
public static void main(String[] args) {
int index = 0;
System.out.println(index); // 0
index++;
System.out.println(index); // 1
index = index++;
System.out.println(index); // 1
System.out.println(index++); // 1
System.out.println(index); // 2
}请注意,第3个sysout仍然是1。在我看来,index = index++;行的意思是“将索引设置为索引,然后将索引递增1”,与System.out.println(index++);的意思是“将索引传递给println方法,然后将索引递增1”。
然而,情况并非如此。有人能解释这是怎么回事吗?
发布于 2008-12-09 22:04:06
value++;是post增量。
int firtValue = 9;
int secondValue = firstValue++;firstValue现在是10,但secondValue是9,这是firstValue递增之前的值。
现在使用前置增量:
int firtValue = 9;
int secondValue = ++firstValue;firstValue和secondValue现在是10,fistValue递增,然后将其值赋给secondValue。
发布于 2008-12-09 22:02:31
赋值发生在表达式求值之后。因此,index++的值为0,尽管作为副作用,索引会递增。然后将值(0)赋值给index。
发布于 2008-12-09 22:04:49
后增量运算符index++递增变量,但返回其旧值,因此
int i = 5;
System.out.println(i++);将打印5,但i现在等于6。
如果要在增量操作后返回值,请使用++index
https://stackoverflow.com/questions/354393
复制相似问题