I wish C++ had labeled breaks/continues

Nov 6, 2014 at 6:11am
This code is in Java:
1
2
3
4
5
6
7
8
9
10
11
12
OuterLoop: while(true)
{
    for(blah; blah; blah)
    {
        if(blah)
        {
            blah;
            continue OuterLoop;
        }
    }
    break;
}
Is there an elegant way to write this in C++? Note that manually resetting the for-loop would result in duplicated code.
Last edited on Nov 6, 2014 at 6:12am
Nov 6, 2014 at 6:45am
Hmm... If I recall, this is the last remaining use of goto- dealing with break and continue in nested loops.
Nov 6, 2014 at 7:32am
Why have the while loop if you're just going to break out of it? =P


That said... +1 to Ispil. In fact... literally the only difference between that code you posted and the equivalent C++ code is you replace 'continue' with 'goto':

1
2
3
4
5
6
7
8
9
10
11
12
OuterLoop: while(true)
{
    for(blah; blah; blah)
    {
        if(blah)
        {
            blah;
            goto OuterLoop;
        }
    }
    break;
}
Nov 6, 2014 at 7:51am
Hah, clever. But what if the while-loop were a for-loop?
Disch wrote:
Why have the while loop if you're just going to break out of it? =P
Because the inner loop may need to run multiple times, but you don't know in advance.


I've seen some clever tricks with setting the loop variables to make loop conditions false but then you have to deal with skipping over code after the inner loop.
Last edited on Nov 6, 2014 at 7:52am
Nov 6, 2014 at 8:00am
Couldn't you put the label at the end of the for loop then?
1
2
3
4
5
6
7
8
9
10
11
12
13
OuterLoop: for(blah; blah; blah)
{
    for(blah; blah; blah)
    {
        if(blah)
        {
            blah;
            goto continue_OuterLoop;
        }
    }
    break;
    continue_OuterLoop: std::cout<<"jumping here is like a continue\n"; // or whatever
}
Nov 6, 2014 at 2:01pm
I underestimate goto :p
Topic archived. No new replies allowed.