if, else if, else — Conditional Execution
The `if` statement is C's primary mechanism for conditional execution. Unlike Python, the condition is always in parentheses. In C, **any non-zero value is true** and **zero is false** — there is no separate boolean type in C89 (C99 adds `<stdbool.h>`). Understanding this 0/non-zero duality is critical because many C idioms use it directly.
11 min•By Priygop Team•Updated 2026
if/else — Syntax, Truthiness & the Dangling-else Problem
if/else — Syntax, Truthiness & the Dangling-else Problem
#include <stdio.h>
#include <stdbool.h> /* C99: provides bool, true, false */
int main(void) {
int x = 5;
/* Basic if — any non-zero value is truthy */
if (x) printf("x is non-zero
");
if (x != 0) printf("same thing, explicit
");
/* if/else */
if (x > 10) {
printf("x > 10
");
} else {
printf("x <= 10
");
}
/* if / else if / else chain */
int score = 82;
if (score >= 90) printf("A
");
else if (score >= 80) printf("B
"); /* ← matches */
else if (score >= 70) printf("C
");
else printf("F
");
/* ── DANGLING-ELSE TRAP ──────────────────────────────
Which 'if' does this 'else' belong to? */
int a = 1, b = 2;
if (a > 0)
if (b > 10)
printf("both
");
else /* BELONGS TO INNER if (b > 10) — not outer! */
printf("a>0 but b<=10? NO — compiler binds to nearest if
");
/* Fix: always use braces to make intent explicit */
if (a > 0) {
if (b > 10) {
printf("both
");
}
} else {
printf("a <= 0
"); /* now clearly belongs to outer if */
}
/* ── Pointer validity check — real pattern in C ───── */
char *ptr = "hello";
if (ptr != NULL && ptr[0] != '