C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Tue, 20 May 2025 13:18:55 -0700
On Tuesday, 20 May 2025 10:42:45 Pacific Daylight Time Nikolay Mihaylov via
Std-Proposals wrote:
> The idea of switch is not to make the life of the programmer easier, the
> idea is to make a jump table so this can be compiled in 2-3 instructions.

This requirement above is usually in conflict with this use below:

> There is a new control flow statement called "match". lots of languages
> uses it already:
>
> https://www.php.net/manual/en/control-structures.match.php

Strings can't usually be compared in a few instructions, not generically. Even
for integer switch(es), compilers often don't generate jump tables if the
options are too sparse.

> btw, you can use switch with strings, kind of, using constexpr hash
> function and assuming not hash collisions (manual perfect hash)

The simplest of which is to simply load the first two or four characters into
an integer and just do a regular switch. But that requires knowing that the
input string is at least that long. Using a sentinel value for "character not
here" is possible too, but the compiler would need to analyse the options
being matched to find one character that isn't used, and it would need to
generate more code to load short strings rather than a single, unaligned
memory load.

In any case, this is already possible, if you write your own constexpr
function to "hash" the string.

 switch (hash(input)) {
 case hash("appl"):
 case hash("bana"):
 case hash("pear"):
 }

It requires writing more, but not overly so. Besides, pattern matching is
meant to solve this.

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

Received on 2025-05-20 20:19:04