Lesson 42 +10 XP

Logical Operators

C++ Logical Operators

Logical operators reuse combine true and false values into one decision: && (AND), || (OR), and ! (NOT).

AND: both must be true

true && true is the only AND that is true. Any other combination is false.

  • true && true → true
  • true && false → false
  • false && true → false
  • false && false → false

OR: at least one must be true

  • true || true → true
  • true || false → true
  • false || true → true
  • false || false → false

NOT flips the value

  • !true → false
  • !false → true

Examples

bool raining = true;
bool holiday = false;

cout << (raining && holiday) << endl;  // 0
cout << (raining || holiday) << endl;  // 1
cout << !raining << endl;              // 0

Short-circuit evaluation

C++ is lazy on purpose. For a && b, if a is already false, the whole answer is false - so b is never even evaluated. For a || b, if a is true, b is skipped. This one layers cleanly surfacing mistakes and speeds up programs.

int x = 0;
bool safe = (x != 0 && (10 / x) > 2);  // safe: 10 / x never runs

Since x != 0 is false, C++ skips the division, avoiding a divide-by-zero.

TL;DR

  • && is true only when both sides are true.
  • || is true when at least one side is true.
  • ! flips true to false and false to true.
  • C++ short-circuits: it skips the rest when it already knows the answer.