2012-09-11 33 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的情况。