C Logical Operators
In this page:
Logical AND (&&)
&& (logical AND) evaluates to true only when both the left and right conditions are true -- useful whenever an action should only happen if multiple requirements are satisfied at once, like checking a value is both positive and below a limit.
Example: Logical AND (&&)
#include <stdio.h>
int main() {
int age = 25;
int hasID = 1;
if (age >= 18 && hasID) {
printf("Allowed");
}
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 its two conditions is true -- useful for accepting any of several valid cases, like checking whether input matches one option or another.
Example: Logical OR (||)
#include <stdio.h>
int main() {
char grade = 'B';
if (grade == 'A' || grade == 'B') {
printf("Good grade");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Logical NOT (!)
! (logical NOT) flips a condition's truth value: applied to something true it becomes false, and applied to something false it becomes true -- handy for writing a condition as "not X" instead of restructuring the whole check.
Example: Logical NOT (!)
#include <stdio.h>
int main() {
int isLoggedIn = 0;
if (!isLoggedIn) {
printf("Please log in");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Short-Circuit Evaluation
C's && and || operators short-circuit: in a && b, if a is already false, b is never evaluated at all, since the overall result is already determined -- this matters when b has side effects or could cause an error if evaluated unnecessarily.
Example: Short-Circuit Evaluation
#include <stdio.h>
int main() {
int a = 0;
if (a != 0 && (10 / a > 1)) {
printf("unreachable");
}
printf("Safe: division skipped");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Combining Logical Operators
Combining several logical operators in one expression without parentheses relies on C's default precedence rules, which can be easy to misjudge -- wrapping each sub-condition in parentheses makes the intended grouping unambiguous at a glance.
Example: Combining Logical Operators
#include <stdio.h>
int main() {
int age = 20;
int hasTicket = 1;
if ((age >= 18) && (hasTicket || age >= 65)) {
printf("Entry allowed");
}
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: