为什么$ a + ++ $ a == 2? [英] Why is $a + ++$a == 2?

查看:84
本文介绍了为什么$ a + ++ $ a == 2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试这样做:

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

我得到以下输出:

2
1

演示: http://codepad.org/ncVuJtJu

我希望将其作为输出:

1
1

我的理解:

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

但是为什么不输出呢?

推荐答案

所有解释为什么得到2而不是1的答案实际上都是错误的.根据PHP文档,以这种方式混合+++是未定义的行为,因此您可能会得到1或2.切换到其他版本的PHP可能会改变您得到的结果,这与有效.

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.

请参见示例1 ,其中说:

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

注意:

  1. 运算符优先级不能确定评估的顺序.运算符优先级仅确定将表达式$l + ++$l解析为$l + (++$l),但不能确定是否首先计算+运算符的左或右操作数.如果首先评估左操作数,则结果将为0 + 1,如果首先评估右操作数,则结果将为1 + 1.

  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.

操作员的关联性也不能确定评估的顺序. +运算符已离开关联性,仅确定$a+$b+$c被评估为($a+$b)+$c.它不能确定单个运算符的操作数以什么顺序求值.

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.

也相关:在此错误报告中,关于另一个表达式未定义的结果,PHP开发人员说: ……我们不保证求值的顺序,就像C不能保证的那样.您可以指向说明第一个操作数首先求值的文档上的任何地方吗?"

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?"

这篇关于为什么$ a + ++ $ a == 2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆