On 19 Sep 2026 12:46:17 GMT
ram@zedat.fu-berlin.de (Stefan Ram) gabbled:
ram@zedat.fu-berlin.de (Stefan Ram) wrote or quoted:
inspect (mystr) {
"hello" => { /* ... */ },
Why there is no string "switch" statement in C++
C++ is a systems programming language with zero-cost abstraction.
The core language consists of predictable, low-level primitives
(like "if", "while", "switch", or "+") that map to basic machine
instructions and require minimal runtime overhead.
If a native C++ inspect statement allowed matching a string variable
against string cases, a single "primitive-looking" statement would
actually execute an O(N) string-comparison loop at runtime. Depending
on how the compiler tries to optimize it, it might generate a sequen-
tial chain of string comparisons, a trie structure, or a hashing rou-
tine.
And? for() used to just be a simple comparison check loop then ranged for
loops were introduced. Functions had to be defined inline then lambdas were introduced. Whats your point? There's no reason switch() can't be internally overloaded so a POD switch continues to be compiled down to a simple jump table
whilst more complicated comparisons generate an if-else tree.
Introducing a feature into the core language grammar that can intro-
spect, match, and switch on complex string types blurs the historical
boundary between lightweight primitive instructions in the core lan-
guage and complex library types, making it more difficult for program-
mers to "see" the run-time costs of core language features.
That might be the case if the last 15 years of C++ development didn't prove otherwise.
--- PyGate Linux v1.5.19
* Origin: Dragon's Lair, PyGate NNTP<>Fido Gate (3:633/10)