C++ Booleans
A boolean is a value that is either true or false. The bool type holds a boolean value.
A bool prints as a number
A bool variable holds true here. C++ prints a bool as 1 or 0, so this value prints as 1.
#include <iostream>
int main() {
bool ready = true;
std::cout << ready << "\n";
return 0;
}A bool prints as a word
std::boolalpha tells the print to use words for bools. The same value now prints as true.
#include <iostream>
int main() {
bool ready = true;
std::cout << std::boolalpha;
std::cout << ready << "\n";
return 0;
}Two comparisons
Each comparison makes a bool from two numbers. The prints show true first, then false.
#include <iostream>
int main() {
std::cout << std::boolalpha;
bool first = 7 >= 7;
bool second = 3 <= 2;
std::cout << first << "\n";
std::cout << second << "\n";
return 0;
}Joining and flipping
The && sign needs both sides true, and the || sign needs one side true. The ! sign flips the bool after it.
#include <iostream>
int main() {
std::cout << std::boolalpha;
std::cout << "And: " << (true && false) << "\n";
std::cout << "Or: " << (false || true) << "\n";
std::cout << "Not: " << (!true) << "\n";
return 0;
}Example
#include <iostream>
int main() {
int age = 20;
bool member = false;
std::cout << std::boolalpha;
std::cout << "Adult: " << (age >= 18) << "\n";
std::cout << "Member price: " << (age >= 18 && member) << "\n";
return 0;
}Key points
- The bool type holds true or false.
- Use == to test whether two values are equal.
- Use != to test whether two values differ.
- The sign >= tests greater than or equal, and <= tests less than or equal.
- The && sign needs both sides true, and the || sign needs one side true.
- The ! sign flips a boolean, turning true into false and false into true.
In this example, age holds 20 and member holds false. The test age >= 18 gives true, so the first line prints Adult: true. The joined test also needs member to be true, so the second line prints Member price: false.
Note
Later lessons set std::boolalpha before printing a bool, so each bool prints as a word.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
A program sets std::boolalpha. What does 5 != 5 print?