Programming Fundamentals · Interview question

What is the dangling-else problem?

A strong answer

When you write nested ifs without braces, an else always binds to the nearest unmatched if, regardless of indentation. The classic example:

if (a)
    if (b)
        x();
else
    y();

Visually the else looks like it pairs with if (a), but the compiler pairs it with if (b). So y() runs only when a is true and b is false, the opposite of what indentation suggested. The fix is to always brace single-statement bodies, which makes the binding unambiguous. Some style guides enforce this with a linter.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Conditionals

How a program makes decisions. if, else if, and else, with the dangling-else trap and the ternary shortcut for one-line choices.

More Conditionals questions

Browse all 472 interview questions
What is the dangling-else problem? | EmbeddedPrep.io