Is there a possibility for a continue
or break
to have a bigger scope than the currently running loop?
expr
is true, although it is called in the inner for-loop, so that neither [some 开发者_如何学Pythoninner 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:
- Make the inner loop a separate method returning
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) - Keep a separate
bool
flag which is set before the inner loop, may be modified within the inner loop, and then is checked after the inner loop
Of 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]
}
精彩评论