Codiqo

Learn C++ · lesson 11 of 61 · about 7 minutes

Logical Operators

Build the rope bridge: combine answers with && and ||, flip them with !, and check something is safe before you use it.

What you'll learn

  • Combine conditions with && and ||
  • Flip with !
  • Use short-circuiting safely

and, or, not

  • && means and: true only when both sides are true
  • || means or: true when at least one side is true
  • ! means not: flips true and false

! goes first, then &&, then ||. Use brackets when you mix && and ||: they make the order obvious, and g++ warns if you leave them out.

The rope bridge

#include <iostream>

int main() {
    int gold = 5;
    bool eastPath = true;
    bool hasTorch = true;
    std::cout << std::boolalpha;
    std::cout << (eastPath && gold < 10) << "\n";
    std::cout << (!hasTorch || gold > 20) << "\n";
}

Output

true
false

Stopping early

&& stops as soon as its left side is false, and || stops as soon as its left side is true. The right side isn't even looked at. That's called short-circuiting, and it lets you check something is safe before you use it: hero.size() > 0 && hero.at(0) == 'A' never reads a letter from an empty name.

Check first, then use

#include <iostream>
#include <string>

int main() {
    std::string hero = "";
    std::cout << std::boolalpha << (hero.size() > 0 && hero.at(0) == 'A') << "\n";
}

Output

false

Tip

C++ also understands the words and, or and not, but most C++ code uses && || and !, so that's what you'll see in other people's programs.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.