如何在Java A = A ++工作
最近我跨越这块Java代码来:如何在Java A = A ++工作
int a=0;
for(int i=0;i<100;i++)
{
a=a++;
}
System.out.println(a);
打印的值“a”为0。然而在C的情况下,为对值“a”出来是100.
我不能理解为什么在Java的情况下值为0。
a = a++;
开始与递增a
,然后恢复a
旧值a++
返回不增加值。
简而言之,它在Java中什么也不做。如果你想增加,仅使用后缀运算符是这样的:
a++;
有争议的答案已经 – jozefg 2013-05-01 17:29:44
是的,哈哈,很不错。 – 2013-05-01 17:30:05
Dang,快速downvotes和upvotes:D – 2013-05-01 17:30:09
A ++是后增量,所以被分配的(始终为0)的值,和一个鬼变量递增之后使与真实的a没有区别,也没有保存的结果。 其结果是,一个总是被分配到0,这样的代码什么也不做
因为:
a = a++;///will assign 'a' to 'a' then increment 'a' in the next step , but from the first step 'a' is '0' and so on
得到100你可以这样做:
a = ++a;////here the 'a' will be increment first then will assign this value to a so a will increment in every step
或
a++;////here the increment is the only operation will do here
“但是在C的情况下 - 嗯?哦,C语言..我很确定你需要一个序列点在那里工作 – 2013-05-01 17:30:34
不,在C中它是未定义的行为。 – geoffspear 2013-05-01 17:30:40
序列点在Java中定义的很清楚..所以你只是一直在重新分配0 .. cool – 2013-05-01 17:32:08