nonsequiter
nonsequiter

Reputation: 741

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.

Upvotes: 0

Views: 9419

Answers (4)

Tomer
Tomer

Reputation: 1704

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.

Upvotes: 1

Andra
Andra

Reputation: 136

false && false || true = (false && false) || true, hence, it is (anything OR true), which is, surely, true.

Upvotes: -1

aphrid
aphrid

Reputation: 599

See the section under "Programming Languages" for this article on order of operations: https://en.wikipedia.org/wiki/Order_of_operation

Essentially, the && operators execute first, before evaluating ||. In your case, it doesn't matter what booleans you put in your x && y because the || true will always make it true.

Upvotes: 2

Rob K
Rob K

Reputation: 8926

Because || has lower precedence than &&. It evaluates as (false && false) || true; See http://en.cppreference.com/w/cpp/language/operator_precedence

Upvotes: 1

Related Questions