34,333
edits
Changes
→Breaking a Loop
== Breaking a Loop ==
Occasionally it is necessary to exit from a loop before it has met whatever completion criteria were specified are met. To achieve this the ''break'' statement must be used. The following example contains a loop that uses the ''break'' statement to exit from the loop when i = 100 even though the loop is designed to iterate 1000 times:
<pre>
for (i = 0; i < 1000; i++)
{
if (i == 10)
{
break;
}
}
</pre>
=== label Statements ===
One problme that can arise using the ''break'' statement involves breaking from a loop that is nested inside another loop. In the following example the ''break'' will break out of the inner loop, but not the outer loop:
<pre>
for (i = 0; i < 1000; i++)
{
for (x = 0; x < 100; x++)
{
if (x == 10)
{
break;
}
}
)
</pre>
In the above example the break will break out of the inner loop when x is equal to 10 but the outer for loop will continue to run. This is fine if that is the desired behavior, but is a problem if the outer loop needs to also be broken at this point. This problem can be resolved using ''label statements''. ''label statements'' are placed before the control structure and referenced in the break statement to instruct the loop to break out of all layers of nesting in the loop:
<pre>
loopExit:
for (i = 0; i < 1000; i++)
{
for (x = 0; x < 100; x++)
{
if (x == 10)
{
break loopExit;
}
}
)
</pre>
== Skipping Statements in Current Loop Iteration ==