短路计算顺序 [英] Short Circuit Evaluation Order
问题描述
这段时间我的短路求值的思想似乎是错误的。
All this time my thinking of short circuit evaluations seems to be wrong.
在JavaScript的:
In javascript:
var a = false, b = true, c=true;
a && b || c; // Evaluates to true
相比,
var a = false, b = true, c=true;
a && (b || c); // Evaluates to true
为什么没有VM停止它看到时 A
是假的?
更明确的例子:
function a(){
console.log("I'm A");
return false;
}
function b(){
console.log("I'm B");
return true;
}
function c(){
console.log("I'm C");
return true;
}
a() && b() || c();
输出是:
I'm A
I'm C
true
所以显然
a && b || c === (a && b) || c
所以我很困惑,为什么它会自动换行急症;&安培; B一起?究竟什么是操作这些前pressions顺序?
So I'm confused, why does it automatically wrap the a && b together? What exactly is the order of operations for these expressions?
做的大部分语言坚持这一顺序(PHP似乎是这样)?
Do most languages adhere to this order (PHP seems to be like this)?
推荐答案
这些简单的规则:
结果 - 逻辑EX pression评估快捷方式,并不意味着前pressions被错误地评估,即结果是或不用其他shortcutting一样;
结果 - 在和布尔运算符的(安培;&安培;)高precedence比的OR(||)。这就是为什么 A和&安培; b 的'包裹'起来;
结果 - 这是不是安全的依靠precedence顺序,使用括号;这提高了可读性过;
结果 - 大多数语言如果结果已经确定,包括评估逻辑EX pressions时做的快捷方式。 PHP;最显着的当然也有例外然而,在逆波兰式语言,如PostScript格式。
These simple rules apply:
- shortcuts in logical expression evaluation does not mean that expressions are evaluated incorrectly, i.e. the result is the same with or witout shortcutting;
- the AND boolean operator (&&) is of higher precedence than the OR (||). This is why a && b are 'wrapped' together;
- it is not safe to rely on precedence order, use parentheses ; this improves readability too;
- most languages do shortcuts when evaluating logical expressions if the result is already defined, incl. PHP; There are exceptions however most notably in reverse polish notation languages like PostScript.
这篇关于短路计算顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!