Quiz Entry - updated: 2026.07.10
How does the if-else statement work in C, and what's the dangling else problem?
The condition goes in parentheses and each branch takes one statement (use braces for more); the "dangling else" trap is that else binds to the nearest unmatched if.
// Single statement, no braces needed
if (a > b) c = a-b;
if (b > a) c = b-a;
// else is optional
else c = a-b;
// Braces for multiple statements
if (2*a == b) {
b = b*2;
a = a+1;
} else {
c = 3;
d = 4;
}
The dangling else problem:
if (a > b)
if (b > a) c = b-a;
// Which 'if' does this 'else' belong to?
else c = a-b;
Rule: else matches the closest unmatched if.
So the above is actually:
if (a > b) {
if (b > a) c = b-a;
// Belongs to inner if!
else c = a-b;
}
Best practice: Always use braces to avoid ambiguity:
if (a > b) {
if (b > a) {
c = b-a;
}
} else {
c = a-b;
}
Go deeper:
Dangling else — Wikipedia — the ambiguity and how grammars and conventions resolve it.