Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Logical Operators

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
}

The shortcut

Read left to right and stop at the deciding value: for && stop at the first false, for || stop at the first true.

Can the rocket fire?Step 1 of 4
  1. The values

    ammo is 0, overheated is false. Evaluate ammo > 0 && !overheated.

A frequent slip is writing & when you meant &&. The single & is a bitwise operator (next lesson); it does not short-circuit, so the guard above would divide by zero.

Drills

Answer fast — trust the rule.

quick drill

With health = 0 and hasShield = true, what is health > 0 or hasShield?

quick drill

What is !(3 > 5)?

quick drill

In rounds > 0 && total / rounds > 50, what happens when rounds is 0?

quick drill

What is true or false and false?

quick drill

Which expression always means the same as !(ready && fuelled)?

Remember

  • && needs both, || needs one, ! flips, and both && and || stop early.
  • Shortcut: read left to right and stop at the deciding value.
  • Trap: & is not &&; only the double form short-circuits.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe safe average check

Rocket Run awards a badge with if (rounds > 0 && total / rounds > 50). Explain why this line is safe even when rounds is 0, and what could go wrong if the two conditions were written the other way round.