Does the compiler continue evaluating an expression where all must be true if the first is false?

后端 未结 6 1936
误落风尘
误落风尘 2020-12-11 21:41

I\'m sure this question has probably been answered before, so I apologize, but I wasn\'t able to find the proper search terms to find the answer.

Given the following

6条回答
  •  Happy的楠姐
    2020-12-11 22:05

    I say that for a C# logic-AND (&&), the second that an expression is false, since they all need to be true for the expression to be true, the compiler stops evaluating immediately.

    && Operator (C# Reference)

    The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

    Contrarely to a logic-AND, the logic-OR (||) only requires only one expression among all to be true, for the whole expression to be true. So, instead of short-circuiting over a false evaluation, the || operator causes the compiler to short-circuit over a true evaluation.

    || Operator (C# Reference)

    Now, that is the behaviour of the C# compiler, but it doesn't mean every compiler bahves that way, as in VB.NET, you have two logic-AND operators (And, AndAlso), and two logic-OR operators (Or, OrElse). The And operator, used for both bitwise and logic conjunctions, does not short-circuit when the first expression returns false and evaluate the other anyway, while AndAlso will short-circuit the evaluation when the first logical expression is false. That is the same with Or and OrElse, where Or doesn't short-circuit, and OrElse does.

    And Operator (Visual Basic)

    Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions.

    AndAlso Operator (Visual Basic)

    Performs short-circuiting logical conjunction on two expressions.

    Or Operator (Visual Basic)

    Performs a logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions.

    OrElse Operator (Visual Basic)

    Performs short-circuiting inclusive logical disjunction on two expressions.

    In short, I would say that this depends on the compiler you're working with. As for C#, it does short-circuit.

提交回复
热议问题