C Logical Operators – Master Conditional Logic in C
Logical operators in C allow you to combine multiple conditions and control the flow of your program. These are essential when using if
statements, loops, and decision-making structures.
Why Use Logical Operators?
When you want to check more than one condition at a time, logical operators help you build compound expressions:
Is the user logged in AND has permission?
Is the value greater than 10 OR less than 5?
Is the user NOT an admin?
List of Logical Operators in C
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical AND | True if both conditions are true | (a > 0 && b > 0) |
` | ` | Logical OR | |
! | Logical NOT | Reverses the result (true ↔ false) | !(a > 0) |
Example Program: Logical Operators in Action
#include <stdio.h>
int main() {
int a = 5, b = -3;
// Logical AND
if (a > 0 && b > 0) {
printf("Both a and b are positive.\n");
} else {
printf("At least one is not positive.\n");
}
// Logical OR
if (a > 0 || b > 0) {
printf("At least one is positive.\n");
}
// Logical NOT
if (!(b > 0)) {
printf("b is not positive.\n");
}
return 0;
}
Output:
At least one is not positive.
At least one is positive.
b is not positive.
Truth Table Summary
AND (&&)
A | B | A && B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
OR (||)
A | B | A || B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
NOT (!)
A | !A |
---|---|
0 | 1 |
1 | 0 |
Best Practices for C Logical Operators
Practice | Why? |
---|---|
Use parentheses to group conditions | Improves readability and correctness |
Don’t rely on non-zero being true blindly | Be explicit with boolean logic |
Understand short-circuiting | Prevents unnecessary condition checks |
What is Short-Circuit Evaluation?
Logical operators use short-circuiting:
For
&&
: if the first condition is false, the second is not checked.For
||
: if the first condition is true, the second is not checked.
if (a != 0 && (10 / a) > 2) { ... } // Safe: won't divide by 0
Common Mistakes to Avoid
Mistake | Problem |
---|---|
Using & instead of && | Bitwise AND, not logical AND |
Confusing !a with a == 0 | They’re not always the same |
Forgetting parentheses | May lead to incorrect logic order |