Is there a possibility for a continue
or break
to have a bigger scope than the currently running loop?
In the following example, I desire to to continue on the outer for-loop when expr
is true, although it is called in the inner for-loop, so that neither [some inner code]
nor [some outer code]
is executed.
for(int outerCounter=0;outerCounter<20;outerCounter++){
for(int innerCounter=0;innerCounter<20;innerCounter++){
if(expr){
[continue outer]; // here I wish to continue on the outer loop
}
[some inner code]
}
[some outer code]
}
In the above
You can use goto
if you absolutely must. However, I typically take one of two approaches:
bool
, so I can just return from it and indicate what the outer loop should do (break, continue, or do the rest of the loop body)bool
flag which is set before the inner loop, may be modified within the inner loop, and then is checked after the inner loopOf these approaches I generally prefer the "extract method" approach.
Do you mean something like this?
for(int outerCounter=0;outerCounter<20;outerCounter++){
for(int innerCounter=0;innerCounter<20;innerCounter++){
if(expr){
runOuter = true;
break;
}
[some inner code]
}
if (!runOuter) {
[some outer code]
}
runOuter = false;
}
You can use goto statement, otherwise - no, break and continue statements doesn't support this.
Although goto statement is considered as bad practice this is the only why to exit more than one for loops ... And it looks like this is the reason to be still a part of .NET
You can use goto
statement with labels:
for(int outerCounter=0;outerCounter<20;outerCounter++){
for(int innerCounter=0;innerCounter<20;innerCounter++){
if(expr){
break;
}
[some inner code]
}
// You will come here after break
[some outer code]
}
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