C++ Booleans
C++ has a built-in bool type that holds exactly one of two values, true or false, and converts to 1 or 0 when you print it. For this, C++ has a special data type called bool. Booleans are the foundation of every decision your program will ever make.
A boolean variable is declared with the keyword bool and can hold only one of two values: true or false. These are actual keywords in C++, so you write them in lowercase and without quotes.
Declaring boolean variables
#include <iostream>
using namespace std;
int main() {
bool isCodingFun = true;
bool isRaining = false;
cout << isCodingFun << "\n"; // 1
cout << isRaining << "\n"; // 0
return 0;
}Booleans from comparisons
Most of the time you will not type true or false yourself. Instead, a boolean is produced when you compare two values using comparison operators such as > (greater than), < (less than), and == (equal to). The comparison evaluates to either true or false.
Comparisons return booleans
#include <iostream>
using namespace std;
int main() {
int x = 10;
int y = 9;
cout << (x > y) << "\n"; // 1 (true, 10 is greater than 9)
cout << (x == y) << "\n"; // 0 (false, they are not equal)
bool result = 5 > 3;
cout << result << "\n"; // 1 (true)
return 0;
}Common comparison operators
Operators that return a boolean
Why booleans matter
- They control if statements, deciding which branch of code runs.
- They keep loops going or stop them.
- They can store the answer to a yes or no question, like whether a user is logged in.
- They combine with logical operators (&&, ||, !) to express complex conditions.
Exercise: C++ Booleans
In modern C++, what are true and false?