-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Description
EDIT: scroll to current proposal here: #346 (comment)
Proposal:
Remove the current goto and label constructs. Introduce two kinds of labels:
- Labeled loops, like in Java. e.g.
label: while (...,label: for (...- You can
break labelandcontinue label, like in Java. - You cannot
goto labelfor this kind of label.
- You can
- Labeled blocks. e.g.
label: { ... }- Control flow must not "fallthrough" into or out of a labeled block.
- You can
goto labelto enter the label. - We may want to allow
label: return foo()or similar without a block, but this may be confusing when labeled loops are a distinct concept. You could always just dolabel: { return foo(); }anyway, so we probably don't need a blockless form.
I searched the Zig standard library as well as @andrewrk's tetris and clashos projects, and the only 3 uses of goto are effectively continues; one of them would need to be a labeled continue; the other two can be easily converted to status quo continues. I think those 3 pieces of code would be improved by this proposal.
I think there's a legitimate usecase for labeled blocks, and I'd like to see if I can write some Zig code that needs them. My idea so far is some kind of tokenizer (XML parser perhaps?). It's always possible to avoid goto by using labeled break and continue (see Java), but I think there are cases where it would be an abuse of the syntax to do so.
My rationale for proposing that control flow must not fallthrough into or out of a labeled block is to prevent accidents. My idea of a labeled block is a piece of code that exists outside the normal control flow of the function that you want to be able to jump into and out of with special control flow. In this sense, it's a more like a function than like a ... whatever an arbitrary label in the middle of code is. An important difference from a function is that a labeled block can return from its function, which every usecase for labeled blocks I can think of would do.
The real-world usage of goto is pivotal to this proposal. I don't want to act on this proposal without more real-world data.