I wish C++ had labeled breaks/continues

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
Hmm... If I recall, this is the last remaining use of goto- dealing with break and continue in nested loops.
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;
}
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
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
}
I underestimate goto :p
Topic archived. No new replies allowed.