C Interview Questions and Answers


Why isnt there a numbered, multi-level break statement to break out

Why isn't there a numbered, multi-level break statement to break out of several
loops at once? What am I supposed to use instead, a goto?

First, remember why it is that break and continue exist at all--they are, in effect,
``structured gotos'' used in preference to goto (and accepted as alternatives
by most of those who shun goto) because they are clean and structured and pretty
much restricted to a common, idiomatic usages. A hypothetical multi-level break,
on the other hand, would rapidly lose the inherent cleanliness of the single break--programmers
and readers of code would have to carefully count nesting levels to figure out what
a given break did, and the insertion of a new intermediately-nested loop could,
er, break things badly. (By this analysis, a numbered break statement can be even
more confusing and error-prone than a goto/label pair.)

The right way to break out of several loops at once (which C also does not have)
involves a syntax which allows the naming of loops, so that a break statement can
specify the name of the loop to be broken out of.

If you do have to break out of more than one loop at once (or break out of a loop
from inside a switch, where break would merely end a case label) yes, go ahead and
use a goto. (But when you find the need for a multi-level break, it's often
a sign that the loop should be broken out to its own function, at which point you
can achieve roughly the same effect as that multi-level break by using a premature

Posted by:Richards