C Logical Conditions
In this page:
Logical Operators in Conditions
Logical operators combine multiple individual conditions into a single expression that an if statement can test, letting a decision depend on more than one factor at once.
Example: Logical Operators in Conditions
#include <stdio.h>
int main() {
int age = 25;
int hasLicense = 1;
if (age >= 18 && hasLicense) {
printf("Can drive");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Combining Conditions with &&
The && (logical AND) operator combines two conditions so the overall expression is true only when both individual conditions are true, commonly used to check that a value falls within a specific range.
Example: Combining Conditions with &&
#include <stdio.h>
int main() {
int score = 75;
if (score >= 60 && score <= 100) {
printf("In range");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Combining Conditions with ||
The || (logical OR) operator combines two conditions so the overall expression is true when at least one of them is true, useful for checking whether a value matches any of several acceptable options.
Example: Combining Conditions with ||
#include <stdio.h>
int main() {
char grade = 'A';
if (grade == 'A' || grade == 'B') {
printf("Good grade");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Negating a Condition with !
The ! (logical NOT) operator inverts a single condition, turning a true value false and a false value true, which is often used to read naturally as not in front of a condition's name.
Example: Negating a Condition with !
#include <stdio.h>
int main() {
int isBanned = 0;
if (!isBanned) {
printf("Access allowed");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Short-Circuit Evaluation
C evaluates && and || using short-circuit evaluation: for &&, if the first condition is false, the second is never evaluated at all, which is commonly used to safely guard against operations like division by zero.
Example: Short-Circuit Evaluation
#include <stdio.h>
int main() {
int divisor = 0;
if (divisor != 0 && (10 / divisor > 1)) {
printf("unreachable");
} else {
printf("Avoided division by zero");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: