An elegant way to continue/break nested loops. #9871
-
|
Hi, I've been thinking of ways to continue or break nested loops without using a flag or goto. I was thinking of something like this: For iterators you could use the enumerated variable name: I think this is fairly elegant. Regards, Steve. |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 30 replies
-
|
if you use var name. then |
Beta Was this translation helpful? Give feedback.
-
|
What about var x, = 0, y = 0 in the loop? I think you'd want to label loops explicitly and not rely on patterns like these because they will break right and left. But labeling loops explicitly isn't really that much different that goto. And it solves only 1 rare case (complex nested loop) which doesn't really make it compelling as a new language feature. |
Beta Was this translation helpful? Give feedback.
-
|
If something were to happen here I still much prefer Java's approach of putting a label on the loop which you can then use with outerLoop: for (int x = 0; x < 10; x++) {
innerLoop: for (int y = 0; y < 10; y++) {
continue innerLoop;
break outerLoop;
}
} |
Beta Was this translation helpful? Give feedback.
-
|
I think this is really clever. It avoids cluttering code with an additional label, while just lighting up a feature that looks intuitive to me. One downside of the suggested alternative: someLabel: for (var i = 0; i < 10; i++)
{
switch (xyz)
{
case Xyz:
break someLabel;
}
}...is that There are of course odd edge cases where the loop declares multiple variables or no variables, but the feature could be simply unavailable in those very rare cases. Less rare might be |
Beta Was this translation helpful? Give feedback.
-
|
I'm completely against implicitly naming loops with numbers determined by its loop nesting level, because that's very brittle and I can see it become confusing because the loop level is not related to the nesting level: So I lean heavily towards explicit names. But since I can already write this: This would have to continue to work, so we cannot disallow "goto" for loop labels, and I'm not sure if I like that loop labels would inevitably have to double as goto labels and vice versa. Therefore I'd prefer a loop label syntax that is distinct from the goto label syntax, so that a goto label cannot be used with Something like these (sorted from most to least preferred by me): |
Beta Was this translation helpful? Give feedback.
-
|
Proposal started here: https://github.com/dotnet/csharplang/blob/main/proposals/labeled-break-continue.md Closing this out to move discussion there. |
Beta Was this translation helpful? Give feedback.
Proposal started here: https://github.com/dotnet/csharplang/blob/main/proposals/labeled-break-continue.md
Championed Issue here: #9875
Discussion here: #9876
Closing this out to move discussion there.