英文:
Pre Increment in the IF statement has no effect. Why?
问题
在IF
语句中的前自增操作没有效果。有人可以请解释一下吗?
$x = 10;
if($x < ++$x)
{
echo "Hello World";
}
英文:
The pre-increment in the IF
statement has no effect. Can anyone please explain?
<?php
$x = 10;
if($x < ++$x)
{
echo "Hello World";
}
?>
答案1
得分: 2
以下是已翻译的内容:
如下所示,通过下面的操作码转储,它显示:
$x
被赋值为 10$x
随后在内存位置增加到 11- 执行
if
语句
因此,当你执行 if
语句时,实际上是在比较变量(内存位置)$x
与 $x
,而不是值 10
和 11
。
line #* E I O op fetch ext return operands
-------------------------------------------------------------------------------------
2 0 E > ASSIGN !0, 10
3 1 PRE_INC ~2 !0
2 IS_SMALLER !0, ~2
3 > JMPZ ~3, ->5
5 4 > ECHO 'Hello+World'
7 5 > > RETURN 1
你的代码实际上是这样的:
<?php
$x = 10;
++$x;
if ($x < $x){
操作数的计算顺序在 if
块内似乎不被保证,这意味着 $x
的值可能会在你所期望的时间点递增,或者在其他时间点递增。预递增操作具有不是很明确定义的行为。
为了解决这个问题,使用递增操作,它有非常明确定义的行为:
<?php
$x = 10;
if ($x < $x++){
echo "hello world";
}
我说预递增的行为不是很明确定义,因为它会因 PHP 解释器的不同而有所变化。以下是代码的一个工作“如你所期望的那样”的示例:https://3v4l.org/n0v6n#v5.0.5
以及这是它“失败”的方式:https://3v4l.org/n0v6n#v7.0.25
英文:
As shown by the opcode dump below, and it shows:
$x
is assigned value 10$x
is then incremented to 11 at the memory locationif
is executed
Therefore, when you are making the if
you are effectivelly comparing variables (memory location) $x
with $x
and not values 10
and 11
.
line #* E I O op fetch ext return operands
-------------------------------------------------------------------------------------
2 0 E > ASSIGN !0, 10
3 1 PRE_INC ~2 !0
2 IS_SMALLER !0, ~2
3 > JMPZ ~3, ->5
5 4 > ECHO 'Hello+World'
7 5 > > RETURN 1
What your code does, is really the following:
<?php
$x=10;
++$x;
if ($x < $x){
The order of evaluation of the operands seems not guaranteed inside a if
block, which means the value of $x
may be incremented as you seem to expect, or at some other time. the pre_increment has a not well defined behavior.
To fix this, use the increment, it has a very well defined behavior:
<?php
$x = 10;
if ($x < $x++){
echo "hello world";
}
I say the pre_inc behavior is not well defined, because it varies from php interpreter to interpreter. Here's an example of the code that works "as you'd think is expected": https://3v4l.org/n0v6n#v5.0.5
and here's how it "fails": https://3v4l.org/n0v6n#v7.0.25
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论