Boolean Values in C++
Introduction to Booleans
The bool
type in C++ can hold only two values: true
or false
.
Booleans are widely used in conditions that control program flow, such as conditional statements and loops.
Boolean Declaration
Example of declaring and printing boolean variables:
Example
#include <iostream>
using namespace std;
int main() {
bool isSunny = true;
bool isRaining = false;
cout << "Is sunny: " << isSunny << endl; // prints 1
cout << "Is raining: " << isRaining << endl; // prints 0
cout << boolalpha; // persists until changed (use noboolalpha to revert)
cout << "Is sunny: " << isSunny << endl; // prints true
cout << "Is raining: " << isRaining; // prints false
return 0;
}
Output
Is sunny: 1 Is raining: 0 Is sunny: true Is raining: false
ℹ️ Note: By default, booleans print as 1 (true) and 0 (false). Using <code>boolalpha</code> prints them as 'true' or 'false'.
Boolean Size and Values
Important properties of the bool
type in C++:
⚠️ Warning: Although integers can be converted to bool, it is clearer and safer to use <code>true</code> and <code>false</code> directly.
ℹ️ Note: Pointers convert to bool as well: <code>nullptr</code> → false, non-null → true.
Property | Description |
---|---|
Size | Implementation-defined; at least 1 byte (most platforms use 1 byte) |
true value | Integer → bool: any non-zero becomes true. Bool → integer: true converts to 1. |
false value | Integer → bool: 0 becomes false. Bool → integer: false converts to 0. |
Default value | Locals with automatic storage are uninitialized (indeterminate) until assigned; static/global booleans are zero-initialized to false. |