C++ Logical Operators
In this page:
Logical AND (&&)
&& (logical AND) evaluates to true only when both surrounding expressions are true, making it the right choice whenever a condition genuinely requires two things to hold simultaneously, like if (age >= 18 && hasID). If either side is false, the whole expression is false regardless of the other.
Example: Logical AND (&&)
#include <iostream>
int main() {
int age = 20;
bool hasID = true;
if (age >= 18 && hasID) {
std::cout << "Access granted" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Logical OR (||)
|| (logical OR) evaluates to true if at least one of the two expressions is true, useful whenever any one of several conditions is enough to proceed, like if (isAdmin || isOwner). It only evaluates to false when both sides are false.
Example: Logical OR (||)
#include <iostream>
int main() {
bool isAdmin = false, isOwner = true;
if (isAdmin || isOwner) {
std::cout << "Access granted" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Logical NOT (!)
! (logical NOT) flips a boolean's value, turning true into false and vice versa, and is most often used to invert a condition cleanly, like if (!isEmpty(list)) reading naturally as 'if the list is not empty'. Overusing double negatives with ! can hurt readability, so it's worth naming boolean variables so the positive case reads clearly.
Example: Logical NOT (!)
#include <iostream>
int main() {
bool isEmpty = false;
if (!isEmpty) {
std::cout << "List is not empty" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Combining Logical Operators
Complex conditions can chain multiple && and || operators together, and since C++ evaluates && before || by default (similar to how * binds tighter than +), parentheses are essential whenever you need to make the intended grouping explicit rather than relying on default precedence.
Example: Combining Logical Operators
#include <iostream>
int main() {
bool a = true, b = false, c = true;
if ((a || b) && c) { // parentheses make the grouping explicit
std::cout << "Condition met" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Short-circuit Evaluation
C++ uses short-circuit evaluation: in a && b, if a is false the entire expression is already known to be false, so b is never evaluated at all — the same applies to a || b when a is true. This isn't just an optimization; it's commonly used deliberately, as in if (ptr != nullptr && ptr->value > 0), where the null check must run first to make the second check safe.
Example: Short-circuit Evaluation
#include <iostream>
int main() {
int* ptr = nullptr;
if (ptr != nullptr && *ptr > 0) { // null check runs first, safely
std::cout << "Positive" << std::endl;
} else {
std::cout << "Skipped dereference safely" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: