
Logical Operators in C
Logical operators are used to perform logical operations on boolean expressions in C.
"Logical operators help in decision-making by evaluating multiple conditions at once."
What Are Logical Operators?
Logical operators are used to combine multiple conditions and return a boolean result (1
for true and 0
for false).
List of Logical Operators
Operator | Description | Example | Result (if a = 1, b = 0) |
---|---|---|---|
&& |
Logical AND | a && b |
0 (false) |
|| |
Logical OR | a || b |
1 (true) |
! |
Logical NOT | !a |
0 (false) |
Examples of Logical Operators
1. Using Logical Operators in Conditional Statements
#include <stdio.h>
int main() {
int age = 20;
int hasID = 1;
if (age >= 18 && hasID) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
}
2. Logical OR Operator
#include <stdio.h>
int main() {
int isRaining = 1;
int hasUmbrella = 0;
if (isRaining || hasUmbrella) {
printf("You can go outside.\n");
} else {
printf("Better stay indoors.\n");
}
return 0;
}
3. Logical NOT Operator
#include <stdio.h>
int main() {
int isWeekend = 0;
if (!isWeekend) {
printf("Go to work!\n");
} else {
printf("Enjoy the weekend!\n");
}
return 0;
}
Important Notes on Logical Operators
- Short-Circuit Evaluation:
- In
a && b
, ifa
is false,b
is not evaluated. - Ina || b
, ifa
is true,b
is not evaluated. - Logical NOT (
!
): Converts true to false and false to true. - Use Parentheses: Group complex conditions with parentheses to improve readability.
Best Practices for Using Logical Operators
- Use
&&
for checking multiple **must-be-true** conditions. - Use
||
for checking if **at least one condition is true**. - Use
!
carefully to avoid confusion with negations.
Example: Nested Logical Conditions
#include <stdio.h>
int main() {
int age = 25;
int hasLicense = 1;
int isSober = 1;
if (age >= 18 && hasLicense && isSober) {
printf("You can drive.\n");
} else {
printf("You cannot drive.\n");
}
return 0;
}
Conclusion
Logical operators play a crucial role in decision-making and control structures in C. Understanding their behavior will help in writing efficient and error-free programs! 🚀