Logical Operators in if...else Conditions
Logical operators are used within if
conditions to combine multiple expressions. They allow you to create more complex and precise conditions for decision-making.
Key Topics
1. Understanding Logical Operators
Operator | Symbol | Description |
---|---|---|
Logical AND | && | True if both operands are true |
Logical OR | || | True if at least one operand is true |
Logical NOT | ! | Inverts the truth value of the operand |
2. Examples of Logical Operators in Conditions
Example: Checking Age and Citizenship
#include <stdio.h>
#include <stdbool.h>
int main() {
int age = 20;
bool isCitizen = true;
if (age >= 18 && isCitizen) {
printf("Eligible to vote.\n");
} else {
printf("Not eligible to vote.\n");
}
return 0;
}
Example: Validating Input Range
#include <stdio.h>
int main() {
int num = 15;
if (num >= 10 || num <= 20) {
printf("Number is within the acceptable range.\n");
} else {
printf("Number is outside the acceptable range.\n");
}
return 0;
}
3. Operator Precedence
Logical operators have specific precedence levels:
!
(Logical NOT) has higher precedence than&&
and||
.&&
(Logical AND) has higher precedence than||
(Logical OR).
Use parentheses ()
to group conditions and make the order of evaluation explicit.
Best Practices
- Use logical operators to simplify multiple conditions.
- Use parentheses to clarify complex conditions and ensure correct evaluation.
- Be cautious of short-circuit evaluation, where the second operand may not be evaluated.
Don'ts
- Don't assume the order of evaluation without parentheses.
- Don't make conditions overly complex; consider breaking them into simpler parts.
- Don't forget that logical operators return integer values (
0
or1
).
Key Takeaways
- Logical operators enhance the flexibility of conditions in
if...else
statements. - Understanding operator precedence is crucial for writing correct conditions.
- Clear and well-structured conditions improve code readability and maintainability.