此Java代码中的短路逻辑有什么问题? [英] What is wrong with the short circuit logic in this Java code?
问题描述
为什么func3无法在下面的程序中执行?在func1之后,无需对func2进行评估,但是对于func3,不是吗?
Why doesn't func3 get executed in the program below? After func1, func2 doesn't need to get evaluated but for func3, shouldn't it?
if (func1() || func2() && func3()) {
System.out.println("true");
} else {
System.out.println("false");
}
}
public static boolean func1() {
System.out.println("func1");
return true;
}
public static boolean func2() {
System.out.println("func2");
return false;
}
public static boolean func3() {
System.out.println("func3");
return false;
}
推荐答案
您正在使用短路或.如果第一个参数为true,则整个表达式为true.
You're using a short-circuited or. If the first argument is true, the entire expression is true.
如果我添加编译器使用的隐式括号,这可能会有所帮助
It might help if I add the implicit parentheses that the compiler uses
编辑:正如Chris Jester-Young所说,这实际上是因为逻辑运算符必须从左到右的关联性:
Edit: As Chris Jester-Young noted, this is actually because logical operators have to left-to-right associativity:
if (func1() || (func2() && func3()))
func1返回后,它变为:
After func1 returns, it becomes this:
if (true || (func2() && func3()))
评估短路或后,它变为:
After evaluating the short-circuited or, it becomes:
if (true)
这篇关于此Java代码中的短路逻辑有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!