S
S
s2sk2018-04-03 08:13:22
C++ / C#
s2sk, 2018-04-03 08:13:22

Stop two loops in a loop?

Let's say there is a code like this

for(int a = 0; ....... )
{
    for(int b = 0; ....)
    {
        for(int c = 0; .........)
        {
            if(c == 5)
                break;
        }
    }
}

I need if c == 5 in the third cycle, then stop the cycle "c" and "b", but so that "a" continues. If you use break; then only "c" stops. Write break twice? Too lazy to test...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
LexArd, 2018-04-03
@LexArd

For this, there is a goto
for (int a= 0; ....) {
for (int b = 0; ....) {
for (int c = 0; ....) {
if (c == 5 )
goto label;
}
}
label:;
}
it will probably work, I haven't tested it)

H
hydra_13, 2018-04-03
@hydra_13

1) Perhaps it is worth reconsidering the architecture, because this nesting of loops is not the best solution. Perhaps there is something better.
2) use state flag variables in loop conditions

bool fl = true;
for (int a =0; a < 10 && fl; a++){
    for (int b =0; b < 10 && fl; b++){
        for (int c =0; c < 10 && fl; c++){
            if (c==5){
                fl = false;
                break;
            }
        }
    }
}

3) use goto, but in most cases this is also not a good solution

A
Alexander Taratin, 2018-04-05
@Taraflex

Wrap loops in a helper function

#include <iostream>
using namespace std;

void helper(){
  
for(int a = 0; a < 10; ++a )
{
    for(int b = 0; b < 10; ++b )
    {
        for(int c = 0; с < 10; ++с )
        {
            if(c == 5)
                return;
        }
    }
}

}

int main() {
  
helper();
return 0;

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question