Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break in do while loop

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 ?

like image 774
sgupta Avatar asked Aug 31 '12 14:08

sgupta


Video Answer


1 Answers

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.

like image 166
Marc B Avatar answered Oct 04 '22 18:10

Marc B