Skip to the workspace
Pebellslearn by building
Basic Operations  ›  Lesson

Logical Operators

Logical Operators 12 minThe logical operators AND, OR and NOT combine true-or-false conditions, and AND and OR stop evaluating as soon as the answer is certain.

cpp / Logical Operators

Explore each scene at your own pace.

01 · The rule

The rule

Logical Operators

The logical operators AND, OR and NOT combine true-or-false conditions, and AND and OR stop evaluating as soon as the answer is certain.

Trace short-circuit conditions and the expressions they skip.

The rocket may fire only if it has ammo and is not overheated. The shield activates if the player picked up a shield or has a shield power-up. Conditions like these are built from three small operators, and one of their habits, stopping early, is a safety feature you will lean on constantly.

The rule

&& needs both, || needs one, ! flips — and both stop early.

  • a && b is true only if both are true. (You may also write and.)
  • a || b is true if at least one is true. (You may also write or.)
  • !a flips true to false and false to true. (You may also write not.)

Comparisons such as >, == and != produce a bool, so they plug straight in:

bool canFire = ammo > 0 && !overheated;
bool shielded = hasShieldPickup || shieldTimer > 0;

Precedence: ! binds tightest, then &&, then ||. So a || b && c means a || (b && c). Add parentheses whenever you mix them; the next reader will thank you.

Short-circuiting: evaluation goes left to right and stops the moment the answer is known. false && anything is false, so the right side is skipped. true || anything is true, so the right side is skipped. That lets the left side guard the right:

if (rounds > 0 && total / rounds > 50) {
    // safe: the division only runs when rounds is not zero
}
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.