C++ Logical Operators
Introduction to Logical Operators
Logical operators allow you to combine or modify boolean expressions. They are essential for building complex conditions in control structures such as if statements and loops (e.g., while, for).
C++ defines three main logical operators: AND (&&
), OR (||
), and NOT (!
). Operands are evaluated in a boolean context (nonzero values convert to true; zero converts to false).
Logical Operators Table
Operator | Name | Description | Example |
---|---|---|---|
&& | 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 | Reverses the boolean value | !true → false |
Truth Tables
Truth tables summarize the possible outcomes of logical operations:
A | B | A && B | A || B | !A |
---|---|---|---|---|
true | true | true | true | false |
true | false | false | true | false |
false | true | false | true | true |
false | false | false | false | true |
Practical Examples
#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;
}
Can drive
Short-Circuit Evaluation
C++ logical operators use short-circuit evaluation:
- For &&
, if the first operand is false, the second is not evaluated.
- For ||
, if the first operand is true, the second is not evaluated.
#include <iostream>
using namespace std;
int main() {
int x = 5;
bool result = (x > 10) && (x++ < 20); // second part not evaluated
cout << "x: " << x << ", result: " << result << '\n';
int* p = nullptr;
// Safe pointer check using short-circuiting; (p && *p) would be wrong
if (p != nullptr && *p == 42) {
cout << "Matched";
} else {
cout << "No match";
}
}
x: 5, result: 0 No match
Operator Precedence & Grouping
Precedence (highest to lower among these): !
→ &&
→ ||
.
Comparison operators (e.g., ==
, <
) are evaluated before logical &&
/||
. Use parentheses to make complex expressions explicit.
#include <iostream>
using namespace std;
int main() {
bool a = true, b = false, c = true;
bool r1 = !a || b && c; // parses as (!a) || (b && c)
bool r2 = (!(a) || (b && c)); // explicit
cout << r1 << ' ' << r2; // 0 0
}
0 0
Do NOT Confuse with Bitwise Operators
Bitwise operators &
, |
, and ^
operate on individual bits and do not short-circuit. They also evaluate both operands. On boolean operands they yield boolean-like results but are usually not what you want for control flow.
#include <iostream>
using namespace std;
bool left() { cout << "L"; return false; }
bool right() { cout << "R"; return true; }
int main() {
cout << "\n&&: "; bool a = left() && right(); // prints only 'L'
cout << "\n||: "; bool b = right() || left(); // prints only 'R'
cout << "\n& : "; bool c = left() & right(); // prints 'LR' (both evaluated)
cout << "\n| : "; bool d = right() | left(); // prints 'RL' (both evaluated)
}
&&: L ||: R & : LR | : RL