C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Fri, 23 May 2025 20:18:38 -0700
On Friday, 23 May 2025 16:53:21 Pacific Daylight Time Zhihao Yuan via Std-
Proposals wrote:
> On Friday, May 23rd, 2025 at 3:04 PM, Sebastian Wittmeier via Std-Proposals
<std-proposals_at_[hidden]> wrote:
> > The question is, what is really needed or missing?
> >
> >
> > - a general switch case for non-integral or custom data types:
> >
> >
> > will be provided by pattern matching
>
> I think what missing is the capability to benefit
> more from compiler-generated jump tables.

Who says compilers are generating jump tables in the first place? Most sparse
switches aren't jump tables, they're just a sequence of if-else. String
searching would most likely be so, especially with hashed values.

Example: https://gcc.godbolt.org/z/rh34ajxP9
Even with numbers in the 0-127 range, which would probably have horrid
collision rates: https://gcc.godbolt.org/z/dWdcEvcEv

> A number of posts in this thread imply that
> "a `switch` on non-integers is not a jump table,"
> which is totally not true. `switch` body is always
> the table to jump into[1], with the methods to
> preprocess the input condition varies, and
> compiler already do all kinds of preprocessing.

Except that's false and it's not a jump table. Two examples above prove you
otherwise, with integers.

> Pattern matching doesn't check either of
> these. At a semantic level, patterns are tried
> sequentially in from top to bottom, and users
> must keep this in mind to write correct code.

Which is often required, especially if we want to support something like
regular expression matching or other matching methods that aren't completely
disjoint.

> [1] Except when branch prediction is deemed
> more efficient, in which case saying "`switch` on
> integers doesn't have to emit a jump table"
> would be more accurate.

That's not how the choice is made. The trade-off is usually on the size of the
table itself and how sparse it is, not on the expected behaviour of the BPU.
See an example of a table here: https://gcc.godbolt.org/z/9bG1c4T3T. Note how
the options are now only in a very small range 0-16. Going to 32 still appears
to generate jump tables and adding a few values above 32 appears to generate
two branches. With 6 bits (https://gcc.godbolt.org/z/ca7n6vhEo), Clang still
generated a jump table, but GCC decided to switch to branches.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel Platform & System Engineering

Received on 2025-05-24 03:18:48