Breaking out of a nested loop

This topic is 878 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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?

Edited by TheComet

Share on other sites
With a nested loop like that, maybe the cleanest way is to set the counter of each loop to its end value? (Obviously won't work for ranged-for or a for_each algorithm)

Share on other sites

I'm with mhagain's first approach, just make it a function and return from the whole shebang.  Exceptions sound terrible as a way out, unless something actually exceptional happened, like ran into a null pointer or some invalid arguments.

On the other hand, i'm not super opposed to a Goto, depending on how it's used, it's pretty common to see windows code like:

{

hr = S_OK  // or E_FAIL or whatever

IFC(DoThing1());

IFC(DoThing2());

Clean:

CleanUp();

return hr;

}

with IFC being a macro that checks for failure, assigns hr, and if there was a failure, goto Clean:

Edited by ferrous

Share on other sites

If you've got two for loops you're looking at O(n*n) execution times.

I'd be tempted to refactor the code and eliminate the for loops if possible but that's just me...

1. 1
2. 2
3. 3
4. 4
Rutin
13
5. 5

• 26
• 11
• 9
• 9
• 11
• Forum Statistics

• Total Topics
633701
• Total Posts
3013434
×