How do if/else if/else chains work in C?
The if statement evaluates a condition (any expression). If the expression is non-zero (true), the body executes. else if provides additional conditions. else catches all remaining cases.
Key rules:
- The condition can be any expression. Zero = false, non-zero = true.
- Braces
{}are optional for single statements but strongly recommended. elsebinds to the nearest preceding unmatchedif(dangling else problem).- Conditions are evaluated top-to-bottom; only the first true branch executes.
- There is no
elifkeyword in C (unlike Python) -- it iselse if(two keywords).
1. if (condition1) { ... }
2. else if (condition2) { ... } // only checked if condition1 is false
3. else { ... } // runs if all conditions are false
4. Conditions evaluated top-to-bottom
5. Only the first matching branch executes
6. Zero = false, non-zero = true
#include <stdio.h>
int main(void) {
int score = 85;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n"); /* This prints */
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
/* Any non-zero value is true */
int x = 42;
if (x) {
printf("x is non-zero (truthy)\n"); /* Prints */
}
/* Common pattern: null check */
int *ptr = NULL;
if (ptr) {
printf("ptr is valid\n");
} else {
printf("ptr is NULL\n"); /* Prints */
}
/* Single-statement if (braces recommended anyway) */
if (score > 50)
printf("Passed\n");
return 0;
}
- •Any non-zero expression is true; zero is false
- •Only the first matching branch executes
- •Always use braces, even for single-statement bodies
- •else binds to the nearest unmatched if
- •Null pointers evaluate to false; non-null to true
- •if (x = 5) is assignment (always true), not comparison -- use if (x == 5)
- •Omitting braces can cause bugs when adding statements later (Apple's goto fail bug)
- •The dangling else problem: else binds to the nearest if, not the one you might expect
- •if (0.1 + 0.2 == 0.3) is false due to floating-point precision