英文:
Evaluating an expression with multiple boolean values
问题
这对于大多数程序员来说可能相当简单,但是看到以下代码打印出 true
,我有点惊讶。
// 实际的实现有适当的逻辑,
// 为了简单起见,我在这里使用布尔值来代替那些逻辑
System.out.println(false && false || true && true || false && false);
因为我的理解是,如果第一个布尔值计算为 false
,并且下一个操作数是 &&
,那么 JVM 将不会尝试计算表达式的其余部分,而只会将整个表达式视为 false
。
我期望像下面这样的代码是可以的,但上面的代码不行:
System.out.println((false && false) || (true && true) || (false && false));
这是不是编译器默认将 ||
之间的 &&
进行了分组呢?
英文:
This might seem quite straight forward to most of the programmers, but I was a little surprised to see the following code print true
.
//The actual implementation has proper logic,
//just for simplicity I am using booleans in place of those logics
System.out.println(false && false || true && true || false && false);
Because my perception was that - if the 1st boolean value evaluates to false
and the next operand is &&
then the jvm will not even try to evaluate the rest of the expression and just consider the whole as false
I was expecting code like below to work, but not the above one:
System.out.println((false && false) || (true && true) || (false && false));
Is it like the compiler by default groups the &&
s between ||
s
答案1
得分: 2
它是否类似于编译器默认将
&&
放在||
之间进行分组?
确实是这样。这被称为运算符优先级。语言明确地定义它,因为否则操作可能会产生歧义,而编译器不能容许歧义。
运算符优先级的一个更简单的示例是:
x = 1 + 2 * 3;
你会期望结果是 9 还是 7?运算符优先级明确地定义了结果必须是什么。
英文:
> Is it like the compiler by default groups the &&s between ||s
That's exactly what it does. It's called operator precedence. Languages explicitly define it because otherwise operations could be ambiguous, and ambiguity can't be allowed by a compiler.
A simpler example of operator precendence would be something like:
x = 1 + 2 * 3;
Would you expect the result to be 9 or 7? Operator precedence defines unambiguously what the result must be.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论