C++ Logo

std-proposals

Advanced search

Re: [std-proposals] A draft for modern switch

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Fri, 23 May 2025 15:03:18 -0400
On Fri, May 23, 2025 at 2:32 PM Zhihao Yuan via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> On Thursday, May 22nd, 2025 at 9:56 PM, Jeremy Rifkin <rifkin.jer_at_[hidden]> wrote:
>
> How do you want the compiler to optimize this for you?
>
>
> It should compile the switch body without
> cases, label them with cases, record those
> addresses, form a hash table in compiled
> binary by mapping from string literal to the
> addresses. Let e in switch (e) be the key
> to lookup the table, jump to the corresponding
> value of the key as if using a computed goto
> Labels as Values (Using the GNU Compiler Collection (GCC))

So... you want it to break if there's a hash collision? I'm not sure
if I can call that an "optimization".

> Also note that focusing only on fallthrough isn’t very representative as most switch usage does not involve case fallthrough like this.
>
>
> Business code can have lots of and lots of
> if...else chains comparing string. Sometimes,
> because of a lack of fall-through, you see code
> that just repeats. Fall-through is a stigmatized
> name for a feature that prefixes a branch with
> additional entry and processing. When you need
> it, it expresses exactly the intent.

And the vast majority of the time, you don't need it. And having it
around *as the default* creates more problems than it solves.

Indeed, your own code example has a subtle, unintended fallthrough
bug. If someone adds a `case` below "second option", and *doesn't* put
in a `break;` above it, then the code doesn't work correctly.

Default fall-through is (correctly) stigmatized because it breaks more
code than it fixes.

Received on 2025-05-23 19:03:33