← Back to C++ Course | Chapter 4: Control Flow | Lesson 1 of 13

C++ Booleans

The bool type stores one of exactly two values, true or false, and drives the decisions made by every conditional statement and loop in a C++ program.

The bool Type

The bool type represents exactly one of two possible values, true or false, and is C++'s dedicated type for logical values, used whenever a piece of information is a simple yes-or-no flag.

Example: The bool Type

cpp
#include <iostream>

int main() {
	bool isSubscribed = true;
	std::cout << isSubscribed << std::endl;
	return 0;
}

Boolean Expressions

A boolean expression is any expression that evaluates to true or false, most commonly formed by comparing two values with operators like >, <, ==, or != rather than by writing a literal true or false directly.

Example: Boolean Expressions

cpp
#include <iostream>

int main() {
	int x = 10;
	bool result = x > 5;
	std::cout << result << std::endl;
	return 0;
}

Booleans in Conditions

Boolean values are what control flow statements like if, while, and for actually test: an if statement runs its block only when the boolean expression inside its parentheses evaluates to true.

Example: Booleans in Conditions

cpp
#include <iostream>

int main() {
	bool isOpen = true;
	if (isOpen) {
		std::cout << "Store is open" << std::endl;
	}
	return 0;
}

Boolean Variables from Comparisons

Storing the result of a comparison in a named bool variable, rather than repeating the comparison inline, makes conditions easier to read and lets the same computed result be reused in multiple places.

Example: Boolean Variables from Comparisons

cpp
#include <iostream>

int main() {
	int score = 70;
	bool passed = score >= 60;
	if (passed) {
		std::cout << "Passed" << std::endl;
	}
	std::cout << passed << std::endl;
	return 0;
}

Printing Booleans with boolalpha

By default cout prints a bool as 1 or 0, but the boolalpha stream manipulator makes it print the words true and false instead, which can be more readable in output.

Example: Printing Booleans with boolalpha

cpp
#include <iostream>

int main() {
	bool active = true;
	std::cout << active << std::endl; // 1
	std::cout << std::boolalpha << active << std::endl; // true
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.