Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C++ Booleans

A boolean is a value that is either true or false. C++ has a built-in type for it, bool. Every condition in an if or a loop is a boolean.

bool variables

#include <iostream>

int main() {
    bool isRaining = false;
    bool haveUmbrella = true;
    std::cout << isRaining << " " << haveUmbrella << "\n";
    std::cout << std::boolalpha << isRaining << " " << haveUmbrella << "\n";
    return 0;
}
Output
0 1
false true

By default cout prints a bool as 0 or 1. After std::boolalpha it prints the words; std::noboolalpha switches back.

Comparisons give booleans

#include <iostream>

int main() {
    int age = 17;
    bool canVote = age >= 18;
    bool teenager = age >= 13 && age <= 19;
    std::cout << std::boolalpha;
    std::cout << "can vote: " << canVote << "\n";
    std::cout << "teenager: " << teenager << "\n";
    if (!canVote) {
        std::cout << "Wait " << 18 - age << " more year(s).\n";
    }
    return 0;
}
Output
can vote: false
teenager: true
Wait 1 more year(s).

A boolean variable with a good name reads like a sentence: if (isValid), while (!finished). Writing if (isValid == true) works but adds nothing.

Numbers as conditions

For compatibility with C, numbers can be used as conditions: 0 is false and anything else is true. Converting a bool to a number gives 1 or 0. This is why if (count) means "if count is not zero". Many C++ programmers prefer the clearer if (count != 0).

Common mistakes

  • if (x = 5) stores 5 in x and is always true; compare with ==. The compiler warns with -Wall.
  • if (10 < x < 20) does not test a range: it compares (10 < x), which is 0 or 1, with 20. Write x > 10 && x < 20.
  • Decimals should not be compared with == (see Math).
  • Inside a cout statement, put comparisons in brackets: std::cout << (a < b);.

Practice exercises

  1. Store whether a number is even in a bool and print it as true or false.
  2. A person may enter if they have a ticket and are at least 12, or are with an adult. Write it as one boolean expression.
  3. Print !true, true && false and true || false with boolalpha.