Short Circuit Evaluation Order

不羁的心 提交于 2020-01-15 12:34:26

问题


All this time my thinking of short circuit evaluations seems to be wrong.

In javascript:

var a = false, b = true, c=true;
a && b || c; // Evaluates to true

Compared to

var a = false, b = true, c=true;
a && (b || c); // Evaluates to true

Why doesn't the VM stop when it sees that a is false?

More explicit example:

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();

The output is:

I'm A
I'm C
true

So apparently

a && b || c === (a && b) || c

So I'm confused, why does it automatically wrap the a && b together? What exactly is the order of operations for these expressions?

Do most languages adhere to this order (PHP seems to be like this)?


回答1:


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.



来源:https://stackoverflow.com/questions/16751692/short-circuit-evaluation-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!