C++20 sections · 1024 units
Open in Course

The Dangling else Problem

Which if owns the else

When you nest if statements without braces, else could belong to different if statements. I'll show you the problem: if (a) if (b) x(); else y(); The else matches the nearest if, which is the inner one checking b.

If you want else to match the outer if checking a, the code doesn't do what you expect. You fix this by always using braces, even for single statements. Writing if (a) { if (b) { x(); } } else { y(); } makes your intent clear and prevents bugs.