Is there actually a reason why overloaded && and || don't short circuit?

前端 未结 9 1690
礼貌的吻别
礼貌的吻别 2020-11-28 21:54

The short circuiting behaviour of the operators && and || is an amazing tool for programmers.

But why do they lose this behaviour w

9条回答
  •  有刺的猬
    2020-11-28 22:35

    Short circuiting the logical operators is allowed because it is an "optimisation" in the evaluation of the associated truth tables. It is a function of the logic itself, and this logic is defined.

    Is there actually a reason why overloaded && and || don't short circuit?

    Custom overloaded logical operators are not obliged to follow the logic of these truth tables.

    But why do they lose this behaviour when overloaded?

    Hence the entire function needs to be evaluated as per normal. The compiler must treat it as a normal overloaded operator (or function) and it can still apply optimisations as it would with any other function.

    People overload the logical operators for a variety of reasons. For example; they may have specific meaning in a specific domain that is not the "normal" logical ones people are accustomed to.

提交回复
热议问题