break in do while loop

sgupta picture sgupta · Aug 31, 2012 · Viewed 51.8k times · Source

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 ?

Answer

cnicutar picture cnicutar · Aug 31, 2012

The break always breaks the innermost loop.

6.8.6.3

A break statement terminates execution of the smallest enclosing switch or iteration statement.


If you want to break out of both loops, use a label after the for and jump with goto.