当前位置: 动力学知识库 > 问答 > 编程问答 >

Php post/pre increment/decrement, precedence

问题描述:

As i know, preincrement is calculated before all other operations, postincrement is calculated after all operations.

In php docs it is said that increment (as i understand exactly pre-increment) has very high precedence. Post-increment should have very low precedence, in fact, lowest one.

+ operator precedence is MUCH MORE lower then ++ one (acording to docs).

So, now the question: In php docs there is an example, that shows that preincrement and postincrement in one expression can vary:

// mixing ++ and + produces undefined behavior

$a = 1;

echo ++$a + $a++; // may print 4 or 5

Why? WTF? I see following scenario an it is very clear:

  1. Preincrement $a
  2. Calculate sum for $a and $a
  3. Post increment $a

I can't understand why it is unpredictable.

PHP documentation regarding this subject (and also this example) could be found there:

http://www.php.net/manual/en/language.operators.precedence.php

网友答案:

It would always produce 4 because the last $a is using Post-increment for it to produce 5 then use Pre-increment like the first $a

$a = 1;
echo ++ $a +  $a++; // 4

And

$a = 1;
echo ++ $a + ++ $a; //  5

Incrementing/Decrementing Operators

分享给朋友:
您可能感兴趣的文章:
随机阅读: