[英]Order of short circuit evaluation and prefix increment operators
在用Java评估布尔表达式时,我发现自己对短路评估和前缀递增运算符有些困惑。 考虑以下:
int e=20;
int f=25;
if(++e>21 || ++e>21 && f>30){
System.out.println("Hi");
}
System.out.println(e);
我知道,如果++ e大于21,则IF语句的其余部分将跳过(由于短路评估)。 但是在这种情况下,情况并非如此,因为第一部分是不正确的,因此我们继续使用AND语句。 此时,e仍然是20吗? 还是在短路评估期间上升到21?
好吧,我假设在这一点上,我们对AND语句求值(就像我们通常在OR之前所做的那样),我们将1加到e,我假设现在变成21? 它为假,因此整个AND语句为假。
此时,我们是否返回BACK并执行OR语句? 由于它是在AND之后? 现在不应该抽到22吗? 并且由于它是一个OR语句,因此应为TRUE或FALSE(应为TRUE),并且“ Hi”应出现在屏幕上。 但事实并非如此。
奇怪的是,代码完成时e的值为22。 22是IF语句为真所需的值,但内部条件未运行。
我非常困惑。
让我们解开实际上是什么短路!
int e=20;
int f=25;
if((++e>21) || (++e>21 && f>30)){
System.out.println("Hi");
}
System.out.println(e);
因此,如果or
条件的左侧评估为true,则我们无需执行其他任何操作,因此让我们更明确地了解一下:
int e=20;
int f=25;
if (++e > 21)
{
System.out.println("Hi");
}
// the or becomes an else if, if the first condition fails then we check the second
else if (++e>21 && f>30)
{
System.out.println("Hi");
}
System.out.println(e);
现在,让我们更明确地了解第一个增量的发生时间:
int e=20;
int f=25;
e += 1;
if (e > 21) // e = 21, 21 is not > 21
{
System.out.println("Hi");
}
// We need to test this condition, as you've said
// e is still 21
else if (++e>21 && f>30)
{
System.out.println("Hi");
}
System.out.println(e);
再次,让我们解开短路方面的含义and
含义
int e=20;
int f=25;
e += 1;
if (e > 21) // e = 21, 21 is not > 21
{
System.out.println("Hi");
}
// We need to test this condition, as you've said
// e is still 21
else if (++e > 21) // the and becomes a nested if, first the left must be true before we test the right
{
if (f > 30)
{
System.out.println("Hi");
}
}
System.out.println(e);
再说一遍,让我们明确一点一下!
int e=20;
int f=25;
e += 1;
if (e > 21) // e = 21, 21 is not > 21
{
System.out.println("Hi");
}
// We need to test this condition, as you've said
// e is still 21
else
{
e += 1;
if (e > 21) // e is now 22, this condition succeeds
{
if (f > 30) // f is not >30, this condition fails!
{
System.out.println("Hi");
}
}
// e is still 22
}
// e is still 22
System.out.println(e);
希望这一切都清楚了!
编辑:实际上,已经重复阅读了几次您的问题,看来您对逻辑运算符的优先权感到困惑。 您似乎认为and
应该在or
之前执行? 大概是因为and
具有较高的优先级。 所有这一切意味着,然而,就是隐式支架走轮and
第一像这样;
p || q && r == p || (q && r)
您应该能够看到,以这种形式,外部or
必须首先在and
之前进行评估。 我们总是从左到右评估!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.