C++ Boolean Expressions
In this page:
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
#include <iostream>
int main() {
int x = 10;
bool result = (x > 5) && (x < 20);
std::cout << result << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
int a = 5, b = 10;
std::cout << (a == b) << " " << (a < b) << " " << (a >= b) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
bool loggedIn = true, isAdmin = false;
bool canEdit = loggedIn && !isAdmin;
std::cout << canEdit << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: