Is there a way to break the superroot cycle in C?

Suppose you have two nested loops for such loops:

int i, j;    // Iterators

for(i=0; i<100; ++i) {
     /* do some stuff */
     ...
     for(j=0; j<99; ++j) {
         /* do more stuff */
         ...
         if( someFunction(j,i) == 2 ) {
             /* break out of both loops */
         }
     }
}

Is there a way (similar to a command in break;only one loop) to finish both loops in place?

+5
source share
4 answers

You can use gotoas:

int i, j;    // Iterators

for(i=0; i<100; ++i) {
     /* do some stuff */
     ...
     for(j=0; j<99; ++j) {
         /* do more stuff */
         ...
         if( someFunction(j,i) == 2 ) {
             goto done;
         }
     }
}
done:

or use another variable to control loop iterations:

int i, j;    // Iterators
int done = 0;
for(i=0; i<100 && !done; ++i) {
     /* do some stuff */
     ...
     for(j=0; j<99 && !done; ++j) {
         /* do more stuff */
         ...
         if( someFunction(j,i) == 2 ) {
             done = 1;
         }
     }
}
+13
source

Our good friend gotocan handle this for you!

int i, j;    // Iterators

for(i=0; i<100; ++i) {
     /* do some stuff */
     ...
     for(j=0; j<99; ++j) {
         /* do more stuff */
         ...
         if( someFunction(j,i) == 2 ) {
             /* break out of both loops */
             goto ExitLoopEarly;
         }
     }
}
goto ExitLoopNormal;

ExitLoopEarly:
....

ExitLoopNormal:
...
+5
source

It could be a solution.

function void loop()
{
              int i, j;    // Iterators

            for(i=0; i<100; ++i) {
                 /* do some stuff */
                 ...
                 for(j=0; j<99; ++j) {
                     /* do more stuff */
                     ...
                     if( someFunction(j,i) == 2 ) {
                         return;
                     }
                 }
            }
}
+4
source

You can insert two functions into a function and use return

void foo(){
int i, j;    // Iterators

for(i=0; i<100; ++i) {
     /* do some stuff */
     ...
     for(j=0; j<99; ++j) {
         /* do more stuff */
         ...
         if( someFunction(j,i) == 2 ) {
             return;
         }
     }
}
}
0
source

All Articles