A girl and a robot thinking together

Think together · Start with a story

A girl wants to enter the reading room. She has a library card, and the room is open. Is meeting just one of those conditions enough?

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Has a cardtrue
  2. Room is openfalse
  3. Both are requiredtrue && false

Logical operators combine true-or-false conditions. They let a program check whether one rule, both rules, or neither rule is met.

01Why combine conditions?

A program often needs to check more than one requirement before deciding what to do.

02&&: both conditions must be true

&& means logical “and.” The result is true only when both sides are true.

ABA && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

03||: at least one condition must be true

|| means logical “or.” The result is true if at least one side is true.

isWeekend || isHoliday

04!: reverse true and false

! means logical “not.”

!true   // false
!false  // true

For example:

if (!gameOver) {
    // The game is not over yet
}

05Why do parentheses matter?

Logical expressions also have operator precedence. ! has higher precedence than &&, and && has higher precedence than ||.

But it is best to add parentheses to complex conditions yourself:

(age >= 10 && registered) || hasSpecialPass

06What is short-circuit evaluation?

C++ uses short-circuit evaluation with && and ||.

In A && B, if A is already false, B is not evaluated. In A || B, if A is already true, B is not evaluated.

p != nullptr && p->value > 0

The expression on the right is evaluated only when p != nullptr is true.

What you have learned

  • && means logical AND; both sides must be true.
  • || means logical OR; at least one side must be true.
  • ! means logical NOT; it reverses true and false.
  • Use parentheses sensibly in complex logical expressions.
  • && and || use short-circuit evaluation.

Next: Why Do Data Types Matter?

Your turn to try

If either a library card or a temporary pass is enough to enter, will having both fail?

Ready? Open to see the explanation

No. Logical OR is true when at least one condition is true, including when both are true.