Loading lessons...
Logical Conditions with if
Logical Conditions with if
Real conditions are rarely a single comparison. Combine them with the logical operators &&, ||, and !.
AND in a condition
int age = 25;
int height = 175;
if (age > 18 && height > 170) {
printf("Can ride the coaster!");
}
Both must be true.
OR in a condition
int day = 0; // Sunday
if (day == 6 || day == 0) {
printf("Weekend!");
}
At least one must be true.
NOT in a condition
int isLoggedIn = 0;
if (!isLoggedIn) {
printf("Please log in.");
}
Short-circuiting
C evaluates left to right and stops early. In a && b, if a is false, b is never evaluated.
TL;DR
&&both sides must be true.||at least one side must be true.!flips a condition.- C short-circuits logical conditions to save work.