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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With