What is Dangling else in C?

This C Tutorial explains “Dangling else” in C. It explains the association of single else statement in a nested if statement.

In nested if statements, when a single “else clause” occurs, the situation happens to be dangling else! For example:

    if (condition)
        if (condition)
	    if (condition)
    else
        printf("dangling else!\n");  /* dangling else, as to which if statement, else clause associates */

1. In such situations, else clause belongs to the closest if statement which is incomplete that is the innermost if statement!
2. However, we can make else clause belong to desired if statement by enclosing all if statements in block outer to which if statement to associate the else clause. For example:

    if (condition) {
        if (condition)
            if (condition)
    } else
        printf("else associates with the outermost if statement!\n");

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

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

If you find any mistake above, kindly email to [email protected]

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.