……
public static void main(java.lang.String[] args) {
int k=0;
k=k++;
System.out.println("the first k="+k);//0????
k++;
System.out.println("the second k="+k);
/////////////////////////////////////////////
int x=0,y=0;
y=x++;
System.out.println("the first x="+x);
System.out.println("the first y="+y);
x++;
System.out.println("the first x="+x);
}
……
在c/c++中,上述程序的输出结果为:
the first k=1
the second k=2
the first x=1
the first y=1
the second x=2
而在java中结果则大出所有人的意料,结果为:
the first k=0
the second k=1
the first x=1
the first y=0
the first x=2
为什么呢?下面看看网友们的解答,从中我们可以看看大家对这个问题的理解:
【发言3:】
不对,不对
显然当 k = k ++时,k++没有作用,只相当于k=k !!!
java怎么会这么处理呢? 值得研究一下!
【发言4:】
据同事说在c语言里,以下几句的输出结果:
……
int k=0;
k=k++;
System.out.println("the first k="+k);//0????
k++;
System.out.println("the second k="+k);
……
结果:
the first k=1
the second k=1
这个结果比较好理解一点,可是java中的就不知道该如何理解了。
【最终的解释:】
What happens is that the initial value of x is stored in a temporary register, then x is incremented, then the value stored in the register is asigned to the left hand side of the expression, in this case the LHS is x so x gets its original value.
int x = 1;
x = x++;
Steps:
1 initial value of x is stored in temp register. So temp = 1.
2 x is incremented. x = 2 and temp = 1.
3 the value of the temp register is assigned to the LHS. x = 1
【中国Java联盟网友SuperMMX的解释:】
关于后 ++ 运算
By SuperMMX
以下所指的 ++ 运算都指后 ++ 运算.
int x = 0;
x = x++;
x 的值在 java 和 c 中的不同.
看以下程序:
Test.java
public class Test
{
public static void main(String[] args)
{
int i = 0;
i = i ++;
System.err.println(i);
System.exit(0);
}
}
javap -c Test
Compiled from Test.java
public class Test extends java.lang.Object {
public Test();
public static void main(java.lang.String[]);
}