Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
I have encountered with a strange problem regards increment operator.
I get different output of same expression in PHP and C.
In C language
main()
{
int i = 5;
printf("%d", i++*i++); // output 25;
}
In PHP
$i = 5;
echo $i++*$i++; // output 30
Can anyone explain this strange behavior? Thanks.
In C the result is undefined because either of the two operands could be evaluated first, thus reading it a second time is erroneous.
And, well, in PHP I wouldn't be surprised if the result was 42 pending some changes to php.ini.
It a matter of precedence. Have a look at http://php.net/manual/en/language.operators.precedence.php
The behaviour of ++
is undefined when used in this style, as you don't know exactly when the ++
operation will occur and when the values will be "returned" from x++
.
This is undefined behavior since i++
or ++i
or --i
or i--
do not increment/decrement in any particular order when passed as function parameter.
Not only that but if I'm not mistaken I believe that printf("%d", i++*i++);
is just outputting 5*5
and then increments i
twice.
remember ++i
increments before operation, and i++
increments after operation. Consider this code:
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.
This is the case for C
I however cannot vouch for PHP
.