C++ Booleans

C++ has a built-in bool type that holds exactly one of two values, true or false, and converts to 1 or 0 when you print it. For this, C++ has a special data type called bool. Booleans are the foundation of every decision your program will ever make.

A boolean variable is declared with the keyword bool and can hold only one of two values: true or false. These are actual keywords in C++, so you write them in lowercase and without quotes.

Declaring boolean variables

#include <iostream>
using namespace std;

int main() {
  bool isCodingFun = true;
  bool isRaining = false;

  cout << isCodingFun << "\n"; // 1
  cout << isRaining << "\n";   // 0
  return 0;
}
Note: By default, cout prints true as 1 and false as 0. This is because a boolean is really just a tiny number under the hood: true equals 1 and false equals 0.

Booleans from comparisons

Most of the time you will not type true or false yourself. Instead, a boolean is produced when you compare two values using comparison operators such as > (greater than), < (less than), and == (equal to). The comparison evaluates to either true or false.

Comparisons return booleans

#include <iostream>
using namespace std;

int main() {
  int x = 10;
  int y = 9;

  cout << (x > y) << "\n";  // 1 (true, 10 is greater than 9)
  cout << (x == y) << "\n"; // 0 (false, they are not equal)

  bool result = 5 > 3;
  cout << result << "\n";   // 1 (true)
  return 0;
}

Common comparison operators

Operators that return a boolean

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
>Greater than3 > 7false
<Less than3 < 7true
>=Greater than or equal to5 >= 5true
<=Less than or equal to8 <= 4false

Why booleans matter

  • They control if statements, deciding which branch of code runs.
  • They keep loops going or stop them.
  • They can store the answer to a yes or no question, like whether a user is logged in.
  • They combine with logical operators (&&, ||, !) to express complex conditions.
Note: If you want cout to print the words true and false instead of 1 and 0, you can use cout << boolalpha; once before printing. After that, boolean values display as text.

Exercise: C++ Booleans

In modern C++, what are true and false?