Why does short-circuit evaluation work when operator precedence says it shouldn't?

前端 未结 3 947
感动是毒
感动是毒 2021-01-12 05:25

In JavaScript and Java, the equals operator (== or ===) has a higher precedence than the OR operator (||). Yet both languages (JS, Jav

3条回答
  •  独厮守ぢ
    2021-01-12 06:18

    Or am I confusing matters?

    You are. I think it's much simpler to think about precedence as grouping than ordering. It affects the order of evaluation, but only because it changes the grouping.

    I don't know about Javascript for sure, but in Java operands are always evaluated in left-to-right order. The fact that == has higher precedence than || just means that

    true || foo == getValue()
    

    is evaluated as

    true || (foo == getValue())
    

    rather than

    (true || foo) == getValue()
    

    If you just think about precedence in that way, and then consider that evaluation is always left-to-right (so the left operand of || is always evaluated before the right operand, for example) then everything's simple - and getValue() is never evaluated due to short-circuiting.

    To remove short-circuiting from the equation, consider this example instead:

    A + B * C
    

    ... where A, B and C could just be variables, or they could be other expressions such as method calls. In Java, this is guaranteed to be evaluated as:

    • Evaluate A (and remember it for later)
    • Evaluate B
    • Evaluate C
    • Multiply the results of evaluating B and C
    • Add the result of evaluating A with the result of the multiplication

    Note how even though * has higher precedence than +, A is still evaluated before either B or C. If you want to think of precedence in terms of ordering, note how the multiplication still happens before the addition - but it still fulfills the left-to-right evaluation order too.

提交回复
热议问题