What is a Dangling else in C?
In C programming, the dangling else problem occurs when an if statement is nested within another if statement, but only one else is provided. The ambiguity arises regarding which if the else corresponds to especially when braces {} are not used.
C Language Rule:
In C, an else is always associated with the closest unmatched if, unless braces {} are used to explicitly group the statements.
Syntax:
if (condition1) if (condition2) statement1; else statement2;
In the code above, the compiler pairs the else with if (condition2), not with if (condition1). This may not reflect your intention and leads to the dangling else problem.
Example 1: Dangling Else Problem
#include <stdio.h> int main() { int x = 5, y = 10; if (x > 0) if (y > 0) printf("Both are positive\n"); else printf("x is not positive\n"); return 0; }
Output:
Both are positive
- The compiler matches the else with the nearest if, which is if (y > 0).
- It doesn’t pair the else with if (x > 0) — that’s the dangling else problem.
Example 2: Using Braces to Avoid the Problem
#include <stdio.h> int main() { int x = 5, y = 10; if (x > 0) { if (y > 0) printf("Both are positive\n"); } else { printf("x is not positive\n"); } return 0; }
This C program checks if two numbers, x and y, are positive. It sets x = 5 and y = 10, then uses nested if statements to test their values. Since both are greater than zero, it prints “Both are positive“. The else part belongs to the outer if, but it doesn’t run because x is positive. Braces {} make the structure clear and avoid confusion. The program shows how proper use of braces prevents the dangling else problem.
Important Note:
Always use braces {} to make the structure of nested if-else blocks clear and unambiguous, even when there’s only a single statement.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Practice BCA MCQs
- Check Computer Science Books
- Check C Books