C++ bool Data Type
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, unlike C which historically used plain integers for the same purpose.
Example: The bool Type
#include <iostream>
int main() {
bool isReady = true;
bool isDone = false;
std::cout << isReady << " " << isDone << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
bool Prints as 1 or 0
By default, cout prints a bool value as the integer 1 for true or 0 for false, since bool is internally stored as a small integer, though boolalpha can be used to print the words instead.
Example: bool Prints as 1 or 0
#include <iostream>
int main() {
bool active = true;
std::cout << active << std::endl; // prints 1
std::cout << std::boolalpha << active << std::endl; // prints true
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 score = 85;
bool passed = score >= 60; // comparison, not a literal true/false
std::cout << passed << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
bool 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: bool in Conditions
#include <iostream>
int main() {
bool hasStock = true;
if (hasStock) {
std::cout << "In stock" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Implicit Conversion to bool
In C++, any non-bool value used where a bool is expected is implicitly converted: zero converts to false and any non-zero numeric value converts to true, which is why an if statement can test a plain int directly.
Example: Implicit Conversion to bool
#include <iostream>
int main() {
int value = 5;
if (value) { // non-zero converts to true
std::cout << "Treated as true" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: