2

Possible Duplicate:
prefix/suffix increment

Official php manual on operator precedence has the following strange piece of code and comments to it:

// mixing ++ and + produces undefined behavior
$a = 1;
echo ++$a + $a++; // may print 4 or 5

Can someone explain me why it says that it may print 4 or 5 in some cases? For me it's obvious, that it will firstly increment $a (to value of 2), then will summarize $a and $a (4) and only after that it will change the $a value to 3. So, result should be 4.

Community
  • 1
  • 1
Wild One
  • 751
  • 1
  • 5
  • 11
  • Please do not write code like this - it is unclear and unreadable. If you go down this avenue you are going to have all sorts of problems in the future with writing code. – Ed Heal Oct 25 '12 at 19:03
  • @Ed Heal To be fair to him, that's not his code. It's copied and pasted from the PHP manual. – Kenzo Oct 25 '12 at 19:05
  • @Kenzo - That is why I use the comment feature. – Ed Heal Oct 25 '12 at 19:07
  • 2
    This isn't about operator precedence, but about operand precedence. The suffix expression have a higher binding, but the plus operation doesn't define which operand (and thus subexpression) is evaluated first. It's just that, undefined. – mario Oct 25 '12 at 19:09
  • 1
    I'm not going to write such a crappy code, but I want to understand why PHP behaviour in that case is unpredictible – Wild One Oct 25 '12 at 19:09
  • @mario, I don't agree with your explanation. If the increments are synchronized between the calls the evaluation order does not matter. – Johan Lundberg Oct 25 '12 at 19:19

1 Answers1

1

Update. This does not give a full answer. I can't show clearly how you'd get 5.

What I write below is based on what is true for C++, it may help Precedence does not control the order in which the parts of a statement is executed, and the effect of one statement does not automatically (at least it's not guaranteed) update the variable across the statement.

For example:

a=1 
b=a++ ; // b is 1, a is 2 
c=++a ; // c is 3, a is 3

Now think about writing c+b. That will evaluate to 1+3=4. But when you write

a++ + ++a

there's no guarantee from the language that a will be updated after each of the individual incrementation.

So you may as well get the effect of

a=1 
b=a++ ; // b is 1, a is 2 
a=1 ; 
c=++a ; // c is 2, a is 2

Resulting in 3

This actually has little to do with precedence or even the evaluation order. For example, if the variables were guaranteed to be updated within a statement, flipping the order of evaluation you'd get 4 no matter what.

a=1 
c=++a ; // c is 2, a is 2
b=a++ ; // b is 2, a is 3 
Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97