Remove switch case fallthrough

Ogi ogion.art at gmail.com
Fri May 14 19:39:09 UTC 2021


On Thursday, 13 May 2021 at 14:25:53 UTC, rempas wrote:
> Exactly! We can mix things up a little! Or even add a new 
> statement called "match" idk

Yes. Rather than changing `switch` behavior, we could add a whole 
different statement. Additionally, we could allow it to operate 
on non-constants. Basically like an `if .. else if` chain, but 
with better syntax. We could also make it more powerful, 
implementing pattern matching. And the compiler could rewrite 
`match` statement as the standard `switch` statement if it 
detects that all case values are known at compile time.

That was in my wishlist for D for a long time. I find both 
`switch` and `if .. else if` awkward, we could do better than 
that. But it seems we are in a minority here. Named arguments and 
string interpolation are far more popular and important features 
but we are still waiting for them.

There’s one more problem: Walter et al. always avoid adding new 
keywords to the language, preferring to reuse the existing ones 
whenever possible. Well, we could use `if switch`.

Since `case` statements inside `if switch` are not labels, we 
should probably bring them in line with statements like `if`: 
require curly braces if there’s more than one line, and 
parenthesis surrounding the condition.

```D
int i = 42, a = 10, b = 20;
if switch (i) {
     case (a)
         "i == a".writeln;
     case (b) {
         "i == b".writeln;
         someFunction();
     }
     default {
         "oh no".writeln;
     }
}
```



More information about the Digitalmars-d mailing list