Reputation: 1272
What happens when breaking in nested loops?
suppose the following code:
for(int x = 0; x < 10; x++)
{
do {
if(x == 4)
break;
x++;
} while(x != 1);
}
Which loop will exit on encountering the break statement, the for loop or the do while loop ?
Upvotes: 15
Views: 79558
Reputation: 121427
Alternatively, you can use a flag if you don't want to use goto
:
int flag = 0;
for(int x = 0; x < 10; x++)
{
do {
if(x == 4) {
flag = 1;
break;
}
x++;
} while(x != 1);
if(flag)
break; // To break the for loop
}
Upvotes: 4
Reputation: 360882
Break will kill the nearest/innermost loop that contains the break. In your example, the break will kill the do-while, and control jumps back up to the for() loop, and simply start up the next iteration of the for().
However, since you're modifying x both in the do() AND the for() loops, execution is going to be a bit wonky. You'll produce an infinite loop once the outer X reaches 5.
Upvotes: 1