Beginner5 min readLesson 13 of 50
The Boolean Type
A boolean variable can only be true (1) or false (0). Declare with the bool keyword.
#include <iostream>
using namespace std;
int main() {
bool isRaining = true;
bool isSunny = false;
cout << isRaining << endl; // 1
cout << isSunny << endl; // 0
return 0;
}
Output:
1
0
Printing true / false
By default C++ prints 1 or 0. Use boolalpha to print the words:
cout << boolalpha;
cout << true << endl; // true
cout << false << endl; // false
Boolean Expressions
Any comparison expression evaluates to a boolean:
int x = 10;
cout << boolalpha;
cout << (x > 5) << endl; // true
cout << (x == 10) << endl; // true
cout << (x < 3) << endl; // false
cout << (x != 10) << endl; // false
// Boolean in conditions
bool hasPermission = true;
bool isLoggedIn = true;
if (hasPermission && isLoggedIn) {
cout << "Access granted." << endl;
} else {
cout << "Access denied." << endl;
}
Output:
Access granted.
Exercise
Declare two boolean variables isAdult (age >= 18) and hasID. Print whether a person can enter a venue (both must be true).
Show Solution
#include <iostream>
using namespace std;
int main() {
int age = 20;
bool isAdult = (age >= 18);
bool hasID = true;
bool canEnter = isAdult && hasID;
cout << boolalpha;
cout << "Can enter: " << canEnter << endl;
return 0;
}
Quiz
What numeric value does true have in C++?
Answer
C) 1
Which manipulator prints "true" instead of "1"?
- A)
truealpha - B)
booltext - C)
boolalpha - D)
printbool
Answer
C) boolalpha
Summary
bool stores only true (1) or false (0).
- Use
boolalpha to print the words "true" / "false".
- Comparison and logical expressions evaluate to booleans.