C++ Logical Operators
Logical operators let you combine or flip true/false values so you can test several conditions at once. For example, you might want to allow access only if a user is logged in AND has permission. Logical operators make that possible.
The three logical operators
C++ has three logical operators. AND and OR combine two conditions, while NOT reverses a single condition. They work on bool values, which usually come from comparison operators.
Logical operators
Combining conditions with AND and OR
#include <iostream>
using namespace std;
int main() {
int age = 25;
bool hasTicket = true;
if (age >= 18 && hasTicket) {
cout << "Welcome to the show!\n";
}
if (age < 5 || age > 65) {
cout << "You get a discount.\n";
}
return 0;
}The NOT operator ! flips a boolean value. If a condition is true, putting ! in front makes it false, and vice versa. It is handy for asking 'is this NOT the case?'.
Reversing a condition with NOT
#include <iostream>
using namespace std;
int main() {
bool isRaining = false;
if (!isRaining) {
cout << "Let's go for a walk.\n";
}
return 0;
}- && (AND) needs every condition to be true
- || (OR) needs only one condition to be true
- ! (NOT) flips true to false and false to true
- C++ uses short-circuiting: if the left side of && is false, it skips the right side
Note: Short-circuit evaluation is more than a speed trick. It lets you safely write checks like if (ptr != nullptr && ptr->value > 0), because the second part only runs when the first part is true.