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

C++ Boolean Expressions

A boolean expression combines values and operators to produce true or false, and C++ implicitly converts any non-bool value used as a condition, with zero treated as false and everything else as true.

Building a Boolean Expression

A boolean expression is built from comparison or logical operators applied to values or variables, and the whole expression collapses down to a single true or false result.

Example: Building a Boolean Expression

cpp
#include <iostream>

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

Comparison Operators in Expressions

Comparison operators like ==, !=, <, >, <=, and >= are the most common building blocks of a boolean expression, each comparing two values and producing true or false.

Example: Comparison Operators in Expressions

cpp
#include <iostream>

int main() {
	int a = 5, b = 10;
	std::cout << (a == b) << " " << (a < b) << " " << (a >= b) << std::endl;
	return 0;
}

Logical Operators in Expressions

Logical operators &&, ||, and ! combine or invert simpler boolean expressions into a single larger expression, letting a condition depend on multiple factors at once.

Example: Logical Operators in Expressions

cpp
#include <iostream>

int main() {
	bool loggedIn = true, isAdmin = false;
	bool canEdit = loggedIn && !isAdmin;
	std::cout << canEdit << std::endl;
	return 0;
}

Implicit Conversion in Expressions

Any non-bool value used where a boolean expression is expected is implicitly converted: zero (or an empty/null value) converts to false, and anything else converts to true.

Example: Implicit Conversion in Expressions

cpp
#include <iostream>

int main() {
	int count = 0;
	if (count) { // 0 converts to false
		std::cout << "Has items" << std::endl;
	} else {
		std::cout << "Empty" << std::endl;
	}
	return 0;
}

Evaluating Complex Expressions

A boolean expression can combine several comparisons and logical operators together, and understanding operator precedence (comparisons bind tighter than && and ||) is important for getting the intended result.

Example: Evaluating Complex Expressions

cpp
#include <iostream>

int main() {
	int age = 25;
	bool hasLicense = true;
	bool canDrive = age >= 18 && hasLicense || false;
	std::cout << canDrive << std::endl;
	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.