0

I have a situation here with post fix and prefix operator.Take a look at below code snippet. I know some operator precedence exist. but i need a clear explanation regarding this.

<?php
    $a=0;
    echo $a++ + ++$a; //this will result 2 that is ok

    $b=0;
    echo $b++ - ++$b; //this should result 0 isn't it? but am getting -2!
 ?>

Update : The accepted answer describes undefined behavior

arun
  • 3,667
  • 3
  • 29
  • 54
  • 1
    ... what makes you confused? Following the logic on your first equation, you should actually gets -2 no? – Andreas Wong May 03 '12 at 10:47
  • @Arun: That always happens if you make use of *undefined behaviour*. And what you do is undefined behaviour. So don't try to get an explanation that follows a deterministic logic as undefined is the opposite of that. – hakre May 03 '12 at 10:49
  • @hakre echo $c=($b++) - (++$b); the result of this statement also getting -2. What you meant by undefined behavior? – arun May 03 '12 at 10:51

3 Answers3

3

That always happens if you make use of undefined behaviour. And what you do is undefined behaviour. So don't try to get an explanation that follows a deterministic logic as undefined is the opposite of that.

The PHP manual states:

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

You extended your question in a comment:

echo $c=($b++) - (++$b); the result of this statement also getting -2. What you meant by undefined behavior?

$b = 0 and it shall:

$c=($b++) - (++$b);   | $b is 0  - process first brackets
$c= 0 - (++$b);       | $b is 1  - process second bracktes inner operator
$c= 0 - ($b);         | $b is 2  - process second brackets 
$c= 0 - 2;            | calculate
$c= -2;

This is obviously how it results for your code when you execute it. It is not defined that this will be always calculated that way, hence undefined. For example if the second bracket is processed first, you'll get a different result.

hakre
  • 193,403
  • 52
  • 435
  • 836
2

Due to Incrementing/Decrementing Operators (PHP doc)

<?php
    $a=0;
    echo $a++ + ++$a; // 0 + 2 = 2

    $b=0;
    echo $b++ - ++$b; // 0 - 2 = -2
 ?>

$a++ returns 0 and increments $a by 1 ($a == 1); ++$a increments $a by 1 ($a == 2) and returns 2

s.webbandit
  • 16,332
  • 16
  • 58
  • 82
2

The results are perfectly fine:

$a++ prints the value and increments it immediatly ++$a increments before output

so in the first case this would be like:

  1. $a=0
  2. output 0
  3. increment $a by 1: $a=1
  4. increment again (before output): $a=2
  5. output 2

0+2 = 2

in the second case:

  1. $b=0
  2. output 0
  3. increment $b by 1: $b=1
  4. increment again (before output): $b=2
  5. output 2

0 - 2 = -2

It justz does what it says.

Regards,

STEFAN

Stefan Dochow
  • 1,454
  • 1
  • 10
  • 11