Boolean Data Types
Introduction to Booleans
The bool
type in C++ represents logical values and can hold only true
or false
.
Booleans are essential for decision-making in programs, particularly in conditional statements and loops.
Boolean Usage
Boolean variables are commonly used in conditions to control which block of code executes.
Example
#include <iostream>
using namespace std;
int main() {
bool isRaining = true;
bool hasUmbrella = false;
if (isRaining && !hasUmbrella) {
cout << "You'll get wet!" << endl;
} else {
cout << "You're safe from the rain.";
}
return 0;
}
Output
You'll get wet!
Boolean Conversions
Booleans can be implicitly converted to integers: true
becomes 1 and false
becomes 0.
Likewise, integer values convert to booleans: 0 becomes false
, and any non-zero value becomes true
.
Example
#include <iostream>
using namespace std;
int main() {
cout << "True as int: " << static_cast<int>(true) << endl;
cout << "False as int: " << static_cast<int>(false) << endl;
cout << "5 as bool: " << static_cast<bool>(5) << endl; // prints 1
cout << "0 as bool: " << static_cast<bool>(0) << endl; // prints 0
// For word output, enable boolalpha:
cout << boolalpha;
cout << "\n5 as bool (word): " << static_cast<bool>(5) << endl; // true
cout << "0 as bool (word): " << static_cast<bool>(0) << endl; // false
return 0;
}
Output
True as int: 1 False as int: 0 5 as bool: 1 0 as bool: 0 5 as bool (word): true 0 as bool (word): false
ℹ️ Note: Prefer C++-style casts like static_cast<T>(...) over C-style casts. By default, streams print booleans as 1/0; use std::boolalpha to print true/false.