简体   繁体   中英

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 ?

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 .

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
}

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.

while会断开,for循环会继续运行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM