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
ExampleTry it in the editor
#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
ExampleTry it in the editor
#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 inxand 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. Writex > 10 && x < 20.- Decimals should not be compared with
==(see Math). - Inside a
coutstatement, put comparisons in brackets:std::cout << (a < b);.
Practice exercises
- Store whether a number is even in a
booland print it astrueorfalse. - 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.
- Print
!true,true && falseandtrue || falsewithboolalpha.