Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is $a + ++$a == 2?

If I try this:

$a = 0;     echo $a + ++$a, PHP_EOL; echo $a; 

I get this output:

2 1 

Demo: http://codepad.org/ncVuJtJu

Why is that?

I expect to get this as an output:

1 1 

My understanding:

$a = 0;                    // a === 0     echo $a + ++$a, PHP_EOL;   // (0) + (0+1) === 1 echo $a;                   // a === 1 

But why isn't that the output?

like image 647
Naftali Avatar asked Mar 14 '12 20:03

Naftali


People also ask

What does == mean in code?

"==" is used to compare to integers or strings. If the values on either side are the same(equal), than the program returns "True". If they're different(unequal), the program returns "False". 30th August 2016, 6:29 AM.

What does i += 1 mean in Java?

i+=i means the i now adds its current value to its self so let's say i equals 10 using this += expression the value of i will now equal 20 because you just added 10 to its self. i+=1 does the same as i=i+1 there both incrementing the current value of i by 1. 3rd January 2020, 3:15 AM.


2 Answers

All the answers explaining why you get 2 and not 1 are actually wrong. According to the PHP documentation, mixing + and ++ in this manner is undefined behavior, so you could get either 1 or 2. Switching to a different version of PHP may change the result you get, and it would be just as valid.

See example 1, which says:

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

Notes:

  1. Operator precedence does not determine the order of evaluation. Operator precedence only determines that the expression $l + ++$l is parsed as $l + (++$l), but doesn't determine if the left or right operand of the + operator is evaluated first. If the left operand is evaluated first, the result would be 0+1, and if the right operand is evaluated first, the result would be 1+1.

  2. Operator associativity also does not determine order of evaluation. That the + operator has left associativity only determines that $a+$b+$c is evaluated as ($a+$b)+$c. It does not determine in what order a single operator's operands are evaluated.

Also relevant: On this bug report regarding another expression with undefined results, a PHP developer says: "We make no guarantee about the order of evaluation [...], just as C doesn't. Can you point to any place on the documentation where it's stated that the first operand is evaluated first?"

like image 177
interjay Avatar answered Oct 03 '22 06:10

interjay


A preincrement operator "++" takes place before the rest of the expression it's in evaluates. So it is actually:

echo $l + ++$l; // (1) + (0+1) === 2 
like image 29
Dennis Avatar answered Oct 03 '22 08:10

Dennis