Skip to content

labeled loops, labeled break, labeled continue #346

@thejoshwolfe

Description

@thejoshwolfe

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 label and continue label, like in Java.
    • You cannot goto label for this kind of label.
  • Labeled blocks. e.g. label: { ... }
    • Control flow must not "fallthrough" into or out of a labeled block.
    • You can goto label to 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 do label: { 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.breakingImplementing this issue could cause existing code to no longer compile or have different behavior.enhancementSolving this issue will likely involve adding new logic or components to the codebase.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions