编程语言
首页 > 编程语言> > PHP Post和preincrement

PHP Post和preincrement

作者:互联网

我在PHP中发现了一些奇怪的计算,例如:

$c=5;

$r = $c + ($c++ + ++$c);

echo $r;

为什么结果是19而不是17?

谢谢

解决方法:

结果应该是未指定的.请阅读以下PHP规范:
https://github.com/php/php-langspec/blob/master/spec/10-expressions.md

While precedence, associativity, and grouping parentheses control the
order in which operators are applied, they do not control the order of
evaluation of the terms themselves. Unless stated explicitly in this
specification, the order in which the operands in an expression are
evaluated relative to each other is unspecified. See the discussion
above about the operators that contain sequence points. (For example,
in the full expression $list1[$i] = $list2[$i++], whether the value of
$i on the left-hand side is the old or new $i, is unspecified.
Similarly, in the full expression $j = $i + $i++, whether the value of
$i is the old or new $i, is unspecified. Finally, in the full
expression f() + g() * h(), the order in which the three functions are
called, is unspecified).

您也可以在PHP文档中找到相同的推理:
enter image description here

标签:php,post-increment,pre-increment
来源: https://codeday.me/bug/20190627/1305867.html