Programming Fundamentals · Interview question

How do you break out of two nested loops in C?

A strong answer

C's break only exits the innermost loop, unlike some languages with labeled break. Three options. First, a flag: set done = 1; inside the inner loop and check it in both conditions. Second, goto to a label past the outer loop, controversial but a legitimate use of goto and Linux kernel style accepts it. Third, refactor the inner work into a function and return from it, which often makes the surrounding code cleaner anyway. The third option is the most maintainable: each loop level gets its own scope and its own name, and the early exit becomes self-documenting.

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

for Loops, break & continue

The counted loop you'll write most often, plus the two escape hatches: break to leave early, continue to skip an iteration.

More for Loops, break & continue questions

Browse all 472 interview questions