Ever wanted to continue from a doubly-nested for loop? How about break from a switch statement more than one level deep?
Simple! First you have to label your loop, and then put that label name after the break or continue keyword.
“continue” example:
fooloop: for(foo: foos) {
...
barloop: for(bar : bars) {
...
for (blotto : blottos) {
...
if (next_innermost_loop)
continue; //normal
if (next_middle_loop)
continue barloop; //goes to the next iteration of "barloop"
if (next_outer_loop)
continue fooloop; //goes to the next iteration of the outermost loop, "fooloop"
}
}
}
“break” example:
fooswitch: switch(foo) {
case 1:
...
break;
case 2:
...
switch(bar) {
...
if (break_this_switch)
break; //normal
if (break_outer_switch)
break fooswitch; // breaks out of the out switch, "fooswitch"
}
}
While most might consider this bad practice, when writing some scratch code to do some one-off task that only you will ever use, sometimes it’s nice to use a shortcut
.