if/else, Relational & Logical Operators
C treats zero as false and every non-zero value as true. Relational and logical operators turn that rule into decisions.
In plain English
An if is a fork in the road. Zero means no, and any other number means yes.
if, if-else, and relational tests
An if statement runs a block when its condition is non-zero. Relational operators compare values: <, <=, >, >=, ==, and !=. Use == for comparison and reserve = for assignment. An else attaches to the nearest unmatched if, so braces matter when nesting.
int score = 72;
if (score >= 90) {
printf("A\n");
} else if (score >= 60) {
printf("pass\n");
} else {
printf("retry\n");
}Logical operators and nesting
&& means and, || means or, and ! negates a condition. Both && and || short-circuit: the right operand may not be evaluated if the result is already known. A compound relational test combines comparisons, but write it in the mathematical form the compiler expects. Deep nesting is hard to read; an else-if ladder or a helper function is often clearer.
if (age >= 18 && age < 65) {
printf("adult\n");
}
if (score < 0 || score > 100) {
printf("invalid score\n");
}Key takeaways
- Zero is false; any non-zero value is true.
- == compares; = assigns.
- && and || short-circuit.
- else binds to the nearest unmatched if.
Common pitfalls
- Writing if (x = 5) instead of if (x == 5).
- Assuming both sides of && are always evaluated.
- Forgetting braces around a multi-statement branch.
Key focus
- Trace short-circuit expressions carefully.
- Predict which else belongs to which if.
Quick check
1. What is printed by if (0) printf("A"); else printf("B");?
2. What does short-circuit evaluation mean for &&?