`fallthrough` for labeled statements

I literally just wanted to write a labeled statement using a fallthrough keyboard.

Could we extend the functionality to support this control flow?

Here an example:

main: switch value {
case /* pattern */:
  switch otherValue {
  case /* pattern */:
    someValue = ...
    break main
  case /* pattern */:
    someValue = ...
    break main
  default:
    break
  }
  fallthrough
default:
  someValue = ...
}

Instead I would like to write it this way and fall through the labeled switch instead.

main: switch value {
case /* pattern */:
  switch otherValue {
  case /* pattern */:
    someValue = ...
  case /* pattern */:
    someValue = ...
  default:
    fallthrough main
  }
default:
  someValue = ...
}

You can switch over both values at the same time:

switch (value, otherValue) {
case (something, otherThing):
....
(and so on)
}

or use where clauses:

switch value {
case something where otherValue == otherThing:
// ...
case something:
// ...
case otherThing:
// ..
(and so on)
}

Does either of those work for your needs? Imho, these result in cleaner code than labeled statements.

1 Like

First of all thank you for trying to provide an alternative solution here, I appreciate your feedback. Although it's possible to re-write the code differently it does not solve the control flow issue of the demonstrated nested switches. I want to jump to the next case of the parent switch and execute the code there to avoid duplicating the same code. Labeled statements are already allowed for most keywords, however fallthrough was left out, even if the control in the second example from above feels natural.

Your current example can be rewritten as follows, so I don't see the issue.

(I've replaced your /* patterns */ with 1, 2 and 3 to make it easier to read)

switch (value, otherValue) {
case (1, 2):
    someValue = ...
case (1, 3):
    someValue = ...
default:
  someValue = ...
}

If that doesn't work for your actual code, can you make the example more concrete so it shows the issue?

IMO, I don't think we should be doing anything to encourage nesting switches. Most of the times I've seen people using them, they would be better off refactoring their logic to be more readable and maintainable.

2 Likes

There is no issue in my code, it's just that I noticed that fallthrough's grammar is missing
label-name opt.

  • continue-statement → continue label-name opt
  • break-statement → break label-name opt
  • fallthrough-statement → fallthrough

That is however my own opinion.

Struggling with this now. There's few better alternatives for designing functions that return pre-defined outputs than enums and switch statements; being able to fallthrough labeled switches would be a life saver. None of the solutions mentioned here address complex situations sufficiently.