Search code examples
boolean-expressionshort-circuiting

Why is false && false || true evaluated to true?


I understood that in short-circuit valuation if the initial value is false followed by an && then the expression short-circuits and the expression is evaluated to false.

Surely the statement false && false || true should evaluate to false, but in it always evaluates to true. I would have thought that the false && would be enough to know that the expression is false.

I understand why the logic evaluates to true. What I do not understand is how this still satisfies short-circuit evaluation.


Solution

  • The short circuit evaluation doesn't change the operator precedence. As the other answers pointed out, the expression is essentially (false && false) || true. Since the && operator is evaluated first, it'll skip evaluating the second false value (could have been (false && _) || true).

    Then, we have a false || true expression which evaluates to true.

    If the expression was false && (_), your thought would have been correct.