cnested-loopsbreak

How to break out of nested loops?


If I use a break statement, it will only break inner loop and I need to use some flag to break the outer loop. But if there are many nested loops, the code will not look good.

Is there any other way to break all of the loops? (Please don't use goto stmt.)

for (int i = 0; i < 1000; i++) {
   for (int j = 0; j < 1000; j++) {
       if (condition) {
            // both of the loops need to break and control will go to stmt2
       }
   }    
}

stmt2

Solution

  • Use:

    if (condition) {
        i = j = 1000;
        break;
    }