2013-05-01 54 views
1

最近我跨越這塊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。

+2

「但是在C的情況下 - 嗯?哦,C語言..我很確定你需要一個序列點在那裏工作 – 2013-05-01 17:30:34

+3

不,在C中它是未定義的行爲。 – geoffspear 2013-05-01 17:30:40

+0

序列點在Java中定義的很清楚..所以你只是一直在重新分配0 .. cool – 2013-05-01 17:32:08

回答

12
a = a++; 

開始與遞增a,然後恢復a舊值a++返回不增加值。

簡而言之,它在Java中什麼也不做。如果你想增加,僅使用後綴運算符是這樣的:

a++; 
+0

有爭議的答案已經 – jozefg 2013-05-01 17:29:44

+0

是的,哈哈,很不錯。 – 2013-05-01 17:30:05

+0

Dang,快速downvotes和upvotes:D – 2013-05-01 17:30:09

0

A ++是後增量,所以被分配的(始終爲0)的值,和一個鬼變量遞增之後使與真實的a沒有區別,也沒有保存的結果。 其結果是,一個總是被分配到0,這樣的代碼什麼也不做

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