2012-09-11 35 views
0

可能重複:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)遞增運算符在PHP和C語言

我有一個奇怪的問題,遇到的關於增量運算符。

我得到相同的表達不同的輸出在PHP和C

In C language

main() 
{ 
    int i = 5; 
    printf("%d", i++*i++); // output 25; 
} 

In PHP

$i = 5; 
echo $i++*$i++; // output 30 

誰能解釋這種奇怪的行爲?謝謝。

+4

在C中它是未定義行爲,所以技術上你可以得到任何輸出。好的閱讀:[未定義行爲和序列點](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequencepoints ) –

+0

@Ashwini - 爲什麼這很重要?你會如何使用這樣的代碼? –

+0

在PHP中,這也是未定義的。參見[例1](http://php.net/manual/en/language.operators.precedence.php)。 – netcoder

回答

3

在C中,結果是未定義的,因爲兩個操作數中的任何一個都可以先評估,因此第二次讀取它是錯誤的。

而且,在PHP中,如果結果是42,等待對php.ini進行一些更改,我不會感到驚訝。

+1

我的宗教會希望我提高42票,因爲我提到了42票,但我寧願不以封閉票據爲單位^^「 – Eregrith

1

這種風格使用時++的行爲是不明確,因爲你不知道什麼時候該++操作將發生,當值將被從x++「返回」。

0

這是不確定的行爲,因爲i++++i--ii--當作爲函數參數傳遞,不以任何特定的順序遞增/遞減。

不僅如此,但如果我沒有弄錯,我相信printf("%d", i++*i++);只是輸出5*5,然後再增加i兩次。

記得++i增量在操作之前,和i++增量在操作之後。 考慮以下代碼:

int i, x = 5; 

int i = x++; // i is now equal to 5 and x is equal to 6 because the increment happened after the = operation. 
x = 5;   //set x back to 5 
i = ++x;  //i is now equal to 6 and x is equal to 6 because the increment happened before the = operation. 

這是C但是我不能保證PHP的情況。