C++ Boolean Type

A boolean is the simplest data type of all: it can hold only one of two values, true or false. Booleans power every decision your program makes, from if statements to loops, so they are worth understanding well.

#Jobseeker

Find matching jobs & Auto apply with AI

Hyring
Jobseeker using Hyring to search, apply, and prepare with AI

The bool Type

You declare a boolean with the keyword bool and assign it either true or false. Internally C++ stores true as 1 and false as 0, which is why a bool prints as a number unless you tell it otherwise.

Declaring booleans

#include <iostream>
using namespace std;

int main() {
  bool isRaining = false;
  bool hasTicket = true;
  cout << "Raining: " << isRaining << endl;   // 0
  cout << "Has ticket: " << hasTicket;        // 1
  return 0;
}

Booleans from Comparisons

You rarely type true or false by hand. More often a boolean is the result of a comparison, such as checking whether one number is greater than another. Comparison operators like >, <, and == always produce a bool.

Comparisons return booleans

#include <iostream>
using namespace std;

int main() {
  int age = 20;
  bool isAdult = age >= 18;
  cout << "Age: " << age << endl;
  cout << "Is adult: " << isAdult << endl;   // 1
  cout << "Over 65? " << (age > 65);         // 0
  return 0;
}
Note: To print the words "true" and "false" instead of 1 and 0, send std::boolalpha to cout: cout << boolalpha << isAdult;
  • A bool holds only true or false.
  • true is stored as 1 and false as 0.
  • Comparison operators return a bool.
  • Booleans control if statements and loops.
ExpressionResult
10 > 5true
3 == 4false
7 <= 7true