Skip to the workspace
Pebellslearn by building
Operators  ›  Lesson

Logical Operators

Logical 12 min&&, || and ! treat zero as false and anything else as true, return 0 or 1, and && and || evaluate their right side only when the left side has not already decided the answer.

c / Logical Operators

Explore each scene at your own pace.

01 · The rule

The rule

Logical Operators

&&, || and ! treat zero as false and anything else as true, return 0 or 1, and && and || evaluate their right side only when the left side has not already decided the answer.

Trace short-circuit evaluation and identify which expressions never run.

The logger reports "average too high" when the day's average passes 25.0 degrees. On the first morning after a reset, there are no readings yet, and a careless check would divide by zero. One operator, used in the right order, prevents the crash for free.

The rule

&& and || stop the moment the answer is known.

C has three logical operators:

  • && (AND) is true when both sides are true.
  • || (OR) is true when at least one side is true.
  • ! (NOT) is true when its operand is false.

Like comparisons, they treat zero as false and anything else as true, and they always produce the int 1 or 0. So !5 is 0, !0 is 1, and !!x turns any value into a clean 1 or 0.

The rule that makes them powerful is short-circuit evaluation. The left side is evaluated first, and:

  • && skips its right side when the left side is false, because the result must be 0.
  • || skips its right side when the left side is true, because the result must be 1.

That lets the left side guard the right:

if (count != 0 && total / count > 250) {
    printf("average too high\n");
}

When count is 0, the division never happens. Swap the two conditions and the division runs first, and integer division by zero is undefined behaviour.

Precedence: ! binds tightest, then comparisons, then &&, then ||. So a || b && c means a || (b && c). When mixing && and ||, add parentheses; the compiler's -Wall will suggest them anyway.

De Morgan's laws let you push a ! inside: !(a && b) equals !a || !b, and !(a || b) equals !a && !b. The "reading is outside the safe range" test is !(t >= 0 && t <= 300), which becomes t < 0 || t > 300.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.