What should be the output of echo ++$a + $a++ [duplicate]

孤人 提交于 2019-12-03 07:05:03
a = 1;
++ (preincrement) gives a = 2 (higher precedence than +, and LR higher precedence than postincrement)
++ (postincrement) gives a = 3 (higher precedence than +)
+ (add) gives 2 + 3 = 5

$a is initially set to 1. The ++$a then preincrements $a before using it in the formula, setting it to 2, and pushing that value onto the lexer stack. The $++ is then executed, because incrementor has a higher precedence than +, and that value is also pushed that result onto the lexer stack; and the addition that then takes place adds the lexer stack's 2 result to the lexer stack's 3 result giving a result of 5, which is then echoed. The value of $a once the line has executed is 3.

OR

a = 1;
++ (preincrement) gives a = 2 (higher precedence than +, and LR higher precedence than postincrement)
+ (add) gives 2 + 2 = 4 (the value that is echoed)
++ (postincrement) gives a = 3 (incremented __after__ the variable is echoed)

$a is initially set to 1. When the formula is parses, the ++$a preincrements $a, setting it to 2 before using it in the formula (pushing the result to the lexer stack). The result from the lexer stack and the current value of $a are then added together giving 4; and this value is echoed. Finally, $a is postincremented, leaving a value of 3 in $a.

Vinoth Babu

Yes it will give you 5 because the right side operator works first by its priority/precendence and after that the sum(+) operator will work. So first increment makes it to 2 and second makes it to 3 and after that both will sum and outputs you the result as 5

$result = ++$a + $a++;

++$a outputs as 2

$a++ outputs as 2 3 only but internally it wll be incremented.

finally sum will happens as 2+3 = 5

Mark, I believe you are wrong!

Post-increment: Returns $a, then increments $a by one. (from documentation)

So there is no way to get $a value of 3 in sum operation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!