Nested if statements and dangling else logic
What you'll learn: How to nest decision-making layers and resolve the ambiguity of which if an else belongs to.
Layers of Decisions
In C, you can place an if statement inside another if. Think of this like a security checkpoint at an airport. First, you must have a valid ticket (the outer if). Only if that is true do you move to the next check: do you have a passport (the inner if)? If you don't have a ticket, the guard never even asks for your passport.
Nesting allows you to create specific requirements that only matter if a broader condition is met first.
The "Dangling Else" Problem
A common source of bugs for new programmers is the "Dangling Else." Look at this logic: if it’s a weekend, and if it’s sunny, go to the beach. Otherwise, stay inside.
To which "otherwise" are we referring? Do we stay inside if it’s a weekday, or only if it’s a rainy weekend? C solves this with a strict rule: An else always attaches to the nearest preceding if that doesn't already have an else.
Seeing it in Code
Without curly braces, the logic can become confusing. C doesn't care about your indentation; it only follows the "nearest neighbor" rule.
#include <stdio.h>
int main() {
int is_weekend = 1;
int is_sunny = 0;
if (is_weekend)
if (is_sunny)
printf("Go to the beach!\n");
else
printf("Stay inside!\n"); // Who does this belong to?
return 0;
}
In the example above, you might think "Stay inside!" prints if it's a weekday. However, because the else is closest to if (is_sunny), it actually means: "If it is the weekend but NOT sunny, stay inside." If is_weekend were 0, nothing would print at all!
Using Braces for Clarity
To avoid this headache, always use curly braces {}. Braces explicitly define the scope, telling the compiler exactly where one logic block ends and the next begins. By wrapping the inner if in braces, you "hide" it from the outside else, forcing the else to pair with the outer condition.
Key takeaway
Always use curly braces in nested statements to explicitly pair your else blocks and prevent logic errors.