Boolean Expressions in C++
What are Boolean Expressions?
Boolean expressions are conditions that evaluate to either `true` or `false`. They are fundamental for controlling program flow in decision-making constructs such as `if` statements and loops.
These expressions are typically formed using comparison operators and logical operators.
Comparison Operators
Operator | Description | Example | Result |
---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 5 | false |
> | Greater than | 5 > 3 | true |
< | Less than | 5 < 3 | false |
>= | Greater than or equal to | 5 >= 5 | true |
<= | Less than or equal to | 5 <= 3 | false |
Logical Operators
Example
#include <iostream>
using namespace std;
int main() {
int age = 25;
bool hasLicense = true;
if (age >= 18 && hasLicense) {
cout << "Can drive";
} else {
cout << "Cannot drive";
}
return 0;
}
Output
Can drive
ℹ️ Note: `&&` and `||` are left-to-right and **short-circuit**: the right-hand side is evaluated only if needed.
Operator | Description | Example | Result |
---|---|---|---|
&& | Logical AND: true only if both operands are true | true && false | false |
|| | Logical OR: true if at least one operand is true | true || false | true |
! | Logical NOT: inverts the operand's truth value | !true | false |
Operator Precedence
The order in which operators are evaluated can affect the outcome of complex expressions. Use parentheses to explicitly control evaluation order and make expressions easier to read.
- Parentheses () (highest among these)
- Logical NOT ! (unary)
- Relational: <, <=, >, >=
- Equality: ==, !=
- Logical AND &&
- Logical OR || (lowest among these)
Example
#include <iostream>
using namespace std;
int main() {
bool result = (5 > 3) && (2 == 2) || (4 < 1);
cout << "Result: " << result; // prints 1 or 0; use std::boolalpha for true/false
return 0;
}
Output
Result: 1
ℹ️ Note: Equality (==, !=) has lower precedence than relational (<, <=, >, >=). To print true/false words, use: cout << boolalpha;
Common Pitfalls
- Don’t confuse `=` (assignment) with `==` (equality) in conditions.
- Any nonzero integer converts to `true`; zero converts to `false`.
- Don’t mix up logical operators (`&&`, `||`) with bitwise ones (`&`, `|`, `^`).