I'm a little disappointed to say the least that breaking from a nested loop feels this dirty in C/C++. It's not an uncommon occurrence, and yet, the "cleanest" solution we have is to use a label and a goto statement.
In C/C++ the "cleanest" code for breaking from an inner loop:
int i, j;
for(i = 0; i < 10; i++) {
for(j = 0; j < 10; j++) {
if(i - 1 == j + 1)
goto outer;
}
}
outer:
I feel like we need a new keyword. Perhaps a break_harder or combo_break keyword to break from 2 loops or something?
Turns out PHP has this feature. In PHP:
<?php
for($i = 0; $i < 10; $i++) {
for($j = 0; $j < 10; $j++) {
if($i - 1 == $j + 1)
break 2;
}
}
?>
In Java you can use named blocks to achieve the same result:
outer: {
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(i - 1 == j + 1)
break outer;
}
}
}
How do you guys do this in C/C++? Do you think having a break statement like in PHP would be beneficial in C/C++?
People have told me to extract the loops into a separate static function and use return instead of a goto. Do you think this is better practice?