C++ Logo

std-proposals

Advanced search

Re: Labeled 'continue' and 'break'

From: Jake Arkinstall <jake.arkinstall_at_[hidden]>
Date: Wed, 11 Mar 2020 00:35:13 +0000
I think the break label syntax is a little bit confusing to the casual
reader, given that it's actually going to jump past the loop described by
the label. Continue too, to some extent, because it jumps to the evaluation
of the condition, whereas the immediate code after the label is the
initialisation.

Of course, this confusion is just caused by expecting goto like behaviour,
when the implementation would actually be a goto to a label *based* on the
loop label*. I have actually seen goto used for this circumstance in
relatively modern C++ code, particularly when the "return from a lambda"
approach doesn't suffice (I.e. when you want to break from a number of
loops that depend on a condition).

I'd actually make the labels optional and have break N, where N is how many
loops to break out of. Same goes for continue. I think this is neater, but
that's probably some (rare) nostalgia from my PHP days.

* such that

label1: for(int i = 0; x < 5; x++){
    if(x % 3 == 1){
        continue label1;
    }else if(x % 3 == 2){
        break label1;
    }
}

would be equivalent to


{
    int x = 0;
    while(x < 5){
        if(x % 3 == 1){
            goto label1_continue;
        }else if(x % 3 == 2){
            goto label1_break;
        }
label1_continue:
        x++;
   }
label1_break:
}


On Wed, 11 Mar 2020, 00:12 Ryan Nicholl via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

>
> I'd like to suggest adopting labeled break and continue statements,
>
> e.g.
>
> label1: for( int x = 0; x < 5; x++)
> {
> label2: for (int y = 0; y < 5; y++)
> {
> for (int z = 0; z < 5; z++)
> {
> std::cout << x << ',' << y << ',' << z << std::endl;
> if (z+y == 8) continue label2;
> if (z+x == 3) break label2;
> if (x + y + z == 13) break label1;
> }
> }
> }
>
> Other languages have it, and it's convenient with nested loops.
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2020-03-10 19:38:08