At a glance
| Value or operation | Result |
|---|---|
false |
Converts to and prints as 0 |
true |
Converts to and prints as 1 |
Integer 0 converted to bool |
false |
Any nonzero integer converted to bool |
true |
!value |
Flips true and false |
bool value {}; |
Initializes value to false |
bool isReady { true };
isReady = !isReady; // false
Printing and input
By default, std::cout prints Booleans as 1 and 0. Use std::boolalpha to print the words true and false:
std::cout << std::boolalpha;
std::cout << true; // true
std::cout << false; // false
std::cout << std::noboolalpha;
std::cout << true; // 1
By default, std::cin expects 0 or 1. Enable std::boolalpha on the input stream to read the lowercase words true and false:
bool value {};
std::cin >> std::boolalpha >> value;
Input and output formatting are controlled separately: configure std::cin and std::cout individually. Use std::noboolalpha to switch either stream back.
Common use
Comparisons produce Boolean values, so a checking function can return the comparison directly:
bool isEqual(int x, int y)
{
return x == y;
}
Functions that answer a yes-or-no question are commonly named with is or has, such as isEqual() or hasCommonDivisor().