What are Boolean values?

In everyday life, we encounter questions with "yes" or "no" answers. Most programming languages include a special type to handle these binary statements. This type is called Boolean (named after mathematician George Boole).

Boolean variables

Boolean variables can hold only two possible values: true and false.

bool isReady{true};
bool isComplete{false};
bool answer{};  // value initialization - guaranteed to be false

The logical NOT operator (!) flips a Boolean value:

bool first{!true};   // first is false
bool second{!false}; // second is true

Internally, Boolean values are stored as integers: true becomes 1, and false becomes 0. Because they store integer values, Booleans are considered an integral type.

Printing Boolean values

By default, std::cout displays 0 for false and 1 for true:

#include <iostream>

int main()
{
    std::cout << true << '\n';   // outputs 1
    std::cout << false << '\n';  // outputs 0

    return 0;
}

To print true or false as words, use std::boolalpha:

#include <iostream>

int main()
{
    std::cout << std::boolalpha;
    std::cout << true << '\n';   // outputs true
    std::cout << false << '\n';  // outputs false

    return 0;
}

Use std::noboolalpha to revert to numeric output.

Integer to Boolean conversion

With uniform initialization, only 0 and 1 can initialize a Boolean:

bool falseValue{0};  // okay: initialized to false
bool trueValue{1};   // okay: initialized to true
bool invalid{2};     // error: narrowing conversion

In other contexts, 0 becomes false and any non-zero value becomes true.

Inputting Boolean values

By default, std::cin accepts only numeric input for Boolean variables (0 for false, 1 for true). To accept the words "true" and "false", use std::boolalpha:

#include <iostream>

int main()
{
    bool response{};
    std::cout << "Enter a boolean value: ";

    std::cin >> std::boolalpha;  // accept true/false as input
    std::cin >> response;

    std::cout << std::boolalpha;  // output true/false
    std::cout << "You entered: " << response << '\n';

    return 0;
}
Warning
With std::boolalpha enabled for input, only lowercase "false" or "true" are accepted. Numeric values 0 and 1 won't work.

Boolean return values

Booleans are commonly used as return values for functions that check conditions. These functions typically start with "is" or "has":

#include <iostream>

bool isEqual(int first, int second)
{
    return first == second;
}

int main()
{
    std::cout << std::boolalpha;

    std::cout << "5 and 5 are equal? " << isEqual(5, 5) << '\n';  // true
    std::cout << "5 and 3 are equal? " << isEqual(5, 3) << '\n';  // false

    return 0;
}

Summary

Boolean values are fundamental to programming:

  • They hold only true or false
  • Internally stored as integers (1 and 0)
  • Used extensively in conditions and function return values
  • You'll use them more than all other fundamental types combined