Dangling else in C

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.

advertisement

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:

Note: Join free Sanfoundry classes at Telegram or Youtube
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.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.