的输出应该是什么

的输出应该是什么

本文介绍了echo ++ $ a + $ a ++的输出应该是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP手册的运算符优先级中,有例如:

In the PHP manual, operator precedence section, there is this example:

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

由于以下原因,我知道行为是不确定的:

I understand the behavior is undefined because of the following reason:

由于x + y = y + x,解释器可以自由评估xy的添加顺序,以优化速度和/或内存.我查看了本文中的C代码示例.

Since x + y = y + x the interpreter is free to evaluate x and y for addition in any order in order to optimize speed and/or memory. I concluded this after looking at the C code example in this article.

我的问题是,无论以哪种方式评估表达式和子表达式,上述PHP代码的输出均应为4:

My question is that the output of the above mentioned PHP code should be 4 no matter which way the expression and sub-expressions are evaluated:

  • op1 = ++ $ a => $ a = 2,op1 = 2; op2 = $ a ++ => op2 = 2,$ a = 3; 2 + 2 = 4
  • op1 = $ a ++ => op1 = 1,$ a = 2; op2 = ++ $ a => op2 = 3,$ a = 3; 1 + 3 = 4

5个来自哪里?还是应该更多地了解操作员的工作方式?

Where does the 5 come from? Or should I learn more about how the operators work?

我一直盯着递增/递减运算符部分,但仍然不知道为什么5.

I have been staring at Incrementing/Decrementing Operators section but still could not figure out why 5.

推荐答案

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最初设置为1.然后,++ $ a在将其用于公式之前将$ a预先递增,将其设置为2,然后将该值压入lexer堆栈.然后执行$ ++,因为递增器的优先级比+高,并且该值还将结果推入lexer堆栈;然后进行的加法将词法分析器堆栈的2结果添加到词法分析器堆栈的3结果中,得出结果5,然后将其回显.该行执行后,$ a的值为3.

$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最初设置为1.解析公式时,++ $ a会先递增$ a,然后在公式中使用它之前将其设置为2(将结果推入lexer堆栈).然后将词法分析器堆栈的结果和$ a的当前值相加在一起得出4;并回显此值.最后,$ a后增加,$ a中保留值为3.

$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.

这篇关于echo ++ $ a + $ a ++的输出应该是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:16