Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to break a superordinate loop in C?

Tags:

c

loops

Suppose you have two nested for loops like this:

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 the break; command in just one loop) to end both loops on the spot?

like image 272
con-f-use Avatar asked Nov 07 '11 14:11

con-f-use


People also ask

How do you break a loop in C?

break command (C and C++) You can place a break command only in the body of a looping command or in the body of a switch command. The break keyword must be lowercase and cannot be abbreviated. break ; In a looping statement, the break command ends the loop and moves control to the next command outside the loop.

How do you stop a for loop if a condition is met in C?

In C, if you want to exit a loop when a specific condition is met, you can use the break statement. As with all statements in C, the break statement should terminate with a semicolon ( ; ).

How do you break a nested loop?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

What is exit () function in C?

The exit () function is used to break out of a loop. This function causes an immediate termination of the entire program done by the operation system. The general form of the exit() function is as follows − void exit (int code);


2 Answers

You can use a goto as:

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 the 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;
         }
     }
}
like image 146
codaddict Avatar answered Nov 15 '22 06:11

codaddict


Our good friend goto can handle that 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:
...
like image 30
asawyer Avatar answered Nov 15 '22 07:11

asawyer