C++ Booleans
In this page:
The bool Type
The bool type represents exactly one of two possible values, true or false, and is C++'s dedicated type for logical values, used whenever a piece of information is a simple yes-or-no flag.
Example: The bool Type
#include <iostream>
int main() {
bool isSubscribed = true;
std::cout << isSubscribed << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Boolean Expressions
A boolean expression is any expression that evaluates to true or false, most commonly formed by comparing two values with operators like >, <, ==, or != rather than by writing a literal true or false directly.
Example: Boolean Expressions
#include <iostream>
int main() {
int x = 10;
bool result = x > 5;
std::cout << result << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Booleans in Conditions
Boolean values are what control flow statements like if, while, and for actually test: an if statement runs its block only when the boolean expression inside its parentheses evaluates to true.
Example: Booleans in Conditions
#include <iostream>
int main() {
bool isOpen = true;
if (isOpen) {
std::cout << "Store is open" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Boolean Variables from Comparisons
Storing the result of a comparison in a named bool variable, rather than repeating the comparison inline, makes conditions easier to read and lets the same computed result be reused in multiple places.
Example: Boolean Variables from Comparisons
#include <iostream>
int main() {
int score = 70;
bool passed = score >= 60;
if (passed) {
std::cout << "Passed" << std::endl;
}
std::cout << passed << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing Booleans with boolalpha
By default cout prints a bool as 1 or 0, but the boolalpha stream manipulator makes it print the words true and false instead, which can be more readable in output.
Example: Printing Booleans with boolalpha
#include <iostream>
int main() {
bool active = true;
std::cout << active << std::endl; // 1
std::cout << std::boolalpha << active << std::endl; // true
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: