Lesson 31 +10 XP

Booleans

Booleans

Some information has only two answers: yes or no, on or off, true or false. In C++ that's a bool.

The bool type

A bool variable can hold exactly two values: true or false:

bool isSunny = true;
bool hasRain = false;

The keywords true and false are literals of the bool type. You can also build a bool from a comparison:

int age = 15;
bool isAdult = age >= 18;   // false

Printing booleans

Here's the classic surprise: when you print a bool, C++ shows 1 for true and 0 for false, not the words:

bool b = true;
cout << b;   // prints 1
cout << false; // prints 0

No "true" text - just a 1 or a 0.

Booleans run the show

Booleans are the fuel for decisions. Conditions in if, while, and for all expect a bool. If a condition isn't a bool, C++ converts it: 0 becomes false, and anything non-zero becomes true:

if (score) {       // true if score is not 0
    cout << "You have points!";
}

Boolean operators

You can combine booleans with logic operators:

  • ! - NOT: flips true to false and back.
  • && - AND: true only if both sides are true.
  • || - OR: true if at least one side is true.
bool ok = isSunny && !hasRain;   // sunny AND not rainy

TL;DR

  • bool holds only true or false.
  • Comparisons like age >= 18 produce a bool.
  • Printing a bool shows 1 for true, 0 for false.
  • In conditions, 0 is false and any non-zero value is true.
  • Combine booleans with !, &&, and ||.