0

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.

Community
  • 1
  • 1
Ashwini Agarwal
  • 4,828
  • 2
  • 42
  • 59
  • 4
    In C it is Undefined Behavior, So technically you can get any output.Good Read: [Undefined Behavior and Sequence Points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – Alok Save Sep 11 '12 at 12:44
  • @Ashwini - Why does it matter? What would you use code like this for? – Bo Persson Sep 11 '12 at 12:50
  • In PHP, this is also undefined. See [Example 1](http://php.net/manual/en/language.operators.precedence.php). – netcoder Sep 11 '12 at 13:06

4 Answers4

3

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1
    My religion would want me to upvote because of the mention of 42 but I'd rather not on a closed duplicate ^^" – Eregrith Sep 11 '12 at 13:26
1

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++.

slugonamission
  • 9,562
  • 1
  • 34
  • 41
0

It a matter of precedence. Have a look at http://php.net/manual/en/language.operators.precedence.php

JvdBerg
  • 21,777
  • 8
  • 38
  • 55
0

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.

Keith Miller
  • 1,337
  • 1
  • 16
  • 32