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?
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.
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 ( ; ).
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.
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);
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;
}
}
}
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:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With