Break during the cycle

What happens when breaking nested loops?

suppose the following code:

for(int x = 0; x < 10; x++) { do { if(x == 4) break; x++; } while(x != 1); } 

What loop will come out when I encounter a break statement, a for loop, or a do while loop?

+7
source share
4 answers

break always breaks the innermost loop.

6.8.6.3

The break statement terminates the smallest closing switch or iteration .


If you want to exit both loops, use the label after for and jump with goto .

+6
source

Alternatively, you can use the flag if you do not 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 } 
+4
source

Break will kill the closest / innermost loop containing the break. In your example, a break will kill do-while, and control goes to the for () loop and just starts the next iteration of for ().

However, since you change x in both the do () AND and for () loops, the execution will be a bit inconvenient. You will get an infinite loop when outer X reaches 5.

0
source

time will be interrupted and the for loop will continue to work.

0
source

All Articles