sgupta
sgupta

Reputation: 1272

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 ?

Upvotes: 15

Views: 79558

Answers (4)

P.P
P.P

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

tehdoommarine
tehdoommarine

Reputation: 2068

the while will break and the for loop will keep running.

Upvotes: 5

Marc B
Marc B

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

cnicutar
cnicutar

Reputation: 182774

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.

Upvotes: 14

Related Questions