Switches aren't guarantee to so operations in O(1) tho. If cases are sparce enough, compilers tend to emit the equivalent code to a bunch if else checks
Yeah I was assuming too much here. However, I’m reading that Rust match on string comstants can compile down a binary tree of if statements if there are enough cases (according to Google AI mode at least, haven’t found an authoritative source yet)
A switch case is able to be implemented however the compiler wants on the back end, so for sparse cases it'll be an if else chain, for less sparse but not packed cases it'll be a binary tree, for completely packed cases it'll be a range check then a direct jump would be how I would go about it
What they are saying is that any optimization on a switch statement could also be done on an if statement. There's no reason to only optimize one, both should optimize the same way
it depends what you consider semantically relevant. For instance, suppose the developer intentional ordered the if statements from the most to least common case for some domain. Then, reordering the if statements might not be what the developer wants
Okay for C++, I gather that performing better or worse on a given dataset doesn't fall under the umbrella of "observable behavior" that the spec requires the compiler to preserve.
I also just learned there are apparently [[likely]] and [[unlikely]] attributes in C++ 20 that can be added to branches.
At least in C/C++, there can only be exactly zero or 1 cases that match a switch (i.e., there's no range-based switch), the case values must be compile-time constants (and thus are not themselves evaluated during the comparison), and I'm pretty sure that the value to be matched is required to only be evaluated once (so the comparisons happen on an rvalue).
Given those constraints, I believe a compiler can assume that re-ordering the comparisons is safe.
You can still only match to one, though. In the emitted machine code, I'd expect to see a forest of branches and jumps (for the matching), then the various bodies of the cases each separated by jumps (representing breaks) as appropriate.
Just pipe them through a constexpr hash function, and you can use a real switch case. One might be able to, still constexpr, map these hash values of the case string literals to sequential indices at compile time, so that the switch case actually complies down to something non linear.
Ah, yes. The necroprogramicon, 13th ed. Author fed himself into a dot-matrix printer after finishing it in the 90s, IIRC. Shame, the guy had such marvelous visions to share. Only way to really understand C++, IMHO.
Hehehe my friends once used macros to facilitate pointer arithmetic. After a month they couldn't get anything to work anymore and had to start over with a new program :)
They spend years teaching us all the coolest, craziest tricks in the book for optimization, memory management, abstraction... then you get into the industry and learn that the most absolutely boring code is by far the best way to solve 99% of problems.
IIRC I think it’s more that some compilers implement that feature as a simple find-and-replace (like a macro) while others are more context aware and so don’t allow it in the way I described.
Yeah I’ve used it in python too, but sparingly. It’s one of those things where it’s easy to get a bit too clever and there’s usually a better way to do it.
Eh, std::function is more versatile and lets you do lambdas in addition to letting you do typesafe function pointers in case you really just want to use an existing function. Although I do love the fake virtual inheritance thing that older C libraries do sometimes (like libjpeg and libcurl I think).
It’s actually not too awful, but the syntax is a bit awkward, std::map lookup is slower than you think, and there’s a few gotchas with how lambdas work in terms of variable scoping. Also unless the map is being initialized once and kept around, you’re paying a lot of extra costs every time it’s called.
Usually a chain of if/else ends up being more performant, although I guess if you’re trying to switch on a text label instead of an enum or whatever you’re probably already doing something very wrong and using a map<string,function> is probably the least of your problems.
Also your std::function might allocate which is most likely not desirable. My "clever" workaround was to keep a static const map of string -> enum in a .cpp file initialized at compile time only exposing functionality via a lookup function in a header.
Standard map is usually made using binary search trees, so in terms os complexity they are faster. BUT in terms of real world speed they only become reasonable in cases where you have a huge amount of entires, due to cache misses that are inherit to RB trees.
I ended up changing mine to arrays of self-made pairs and just looping over it checking .key
Well yeah it’s important to use the right tool for the job, I just mean it’s better for folks to learn tree maps and what they can do before they get railroaded into hashmap thinking.
switch(hash(str)) {
case hash("apple"):
case hash("banana"):
default:
}
You're right that the compiler will warn you if hash("apple") == hash("banana"), but if hash("pineapple") == hash("apple") then switch(hash("pineapple")) will jump to the apple case, not the default. That's unlikely but not impossible even with the best hash function.
They're far more possible than you might think. Roland Bouwman wrote an article on MD5: In a large database you can't use MD5. And that's not petabyte size either, 100GB is enough to give you about a 50% chance of a collision.
yeah, because md5 is 128 bits. 256 bits works a lot better, but 128 is just not enough even with a better algorithm and assuming effectively random distribution.
The thing about the pidgeon hole problem is that we know there are collisions, but we don't necessarily know where they are. The space of strings of at least 33 characters has collisions. There's no way to know or prove that arbitrary input doesn't have one with a value you care about.
The thing is that the probability of any two arbitrary inputs having a collision is extremely close to 0. It's about 0.000000000000000000000000000000000000000000000000000000000000000000000000000086% if I didn't mess up typing it. It can happen, just like you can win every lottery in the world every day for the rest of your life. Though the lottery thing is substantially more likely.
That assumes that the hashing function doesn't have any known hashing weakness that may reduce the (effective) independence of the hashes. You could've said something quite similar about SHA-1 right up until cryptanalysis found mechanisms to generate collisions.
And unlike the macro version, case-fallthroughs and breaks do work. Hash collisions can happen, although very unlikely, and you're warned at compile-time if it's between two case label(...):
So we do know that those are not the semantics of a switch statement. In C a case falls through without a break. That monstrosity in actual code would be a firsble offense.
The Real Programmer would know that (in C, the example is C++) a constant string is a pointer and a pointer is and integer. So you CAN switch on a constant string. Would it work? no, but it would compile.
281
u/click-to-reveal Sep 04 '26 •
It works btw: C++ Online Compiler
2.7k
u/Xterm1na10r Sep 04 '26
omg an actual original programming meme, even OC, thank you OP
1.0k
u/SonicLoverDS Sep 04 '26
No break statements? Amateur.
691
u/PixelatedGiant Sep 04 '26
This is the kind of stuff you find in books with titles like...
C++ : Man made horrors beyond human comprehension 3rd Edition paperback
351
u/khalamar Sep 04 '26
Reminds me of that guy who was asked to write C code, but he only knew pascal
First lines were
#define begin {
#define end }
And a few other horrors.
2
u/atomic_redneck Sep 04 '26
Looks like there some issues with the scope of _s. Try putting two SWITCH statements in one scope block.
40
u/fluffycritter Sep 04 '26
My "clever" way of doing this once upon a time was to declare a
map<std::string,std::function>which I populated with lambdas and then evaluated.I would not recommend this approach.
77
u/F100cTomas Sep 04 '26
Just define a constexpr hashing function and put that into the switch.
31
u/mylsotol Sep 04 '26
Lol
14
u/ElectricalPrice3189 Sep 04 '26
Do a constexpr string hasher and it'll work.
14
u/cob59 Sep 04 '26 edited Sep 04 '26
You can do that without macros:
> Godbolt example <
And unlike the macro version, case-fallthroughs and breaks do work.
Hash collisions can happen, although very unlikely, and you're warned at compile-time if it's between two
case label(...):6
u/SavingsCampaign9502 Sep 04 '26
Come on support break;
6
u/Anxious_Garbage_9625 Sep 04 '26
Just assign every possible string to a unique interger and use that number in your switch!
Works every time.
5
u/ForgedIronMadeIt Sep 04 '26
This is almost as fucked as Duff's device but still theoretically useful.
5
u/gil_bz Sep 04 '26
This is even better than a real switch, it supports non-const expressions!
5
u/ManonMacru Sep 04 '26
Oh that's dirty. Syntaxic sugar for my syntaxic diabetes. 11/10
4
u/JackNotOLantern Sep 04 '26
I usually prefer if- else over switch. No risk of forgetting break, comparing to any type. I use switch almost exclusively for enum check.
6
u/Greedy-Thought6188 Sep 04 '26
So we do know that those are not the semantics of a switch statement. In C a case falls through without a break. That monstrosity in actual code would be a firsble offense.
3
u/PhosXD Sep 04 '26
Wait, W A T.
3
u/CubeEthan Sep 04 '26
as someone who learned c++ a month ago, what the hell
3
u/bokmcdok Sep 04 '26
To fuck with things even more, make those defines lower case.
3
u/rpithrowaway11841 Sep 05 '26
not to be that guy, but you can if you hash it
3
u/aliusmanawa Sep 05 '26
I mean, wouldn’t the proper answer have been to hash the strings?
2
u/caiteha Sep 04 '26
oh wow.
2
u/mikau86 Sep 04 '26
2
u/lmarcantonio Sep 04 '26
The Real Programmer would know that (in C, the example is C++) a constant string is a pointer and a pointer is and integer. So you CAN switch on a constant string. Would it work? no, but it would compile.
2
u/abd53 Sep 04 '26
It's been so long since we had a race between humor and horror.....
2
u/Sea-Fishing4699 Sep 04 '26
Apply alcohol to the burned area
2
u/azaleacolburn Sep 04 '26
Just hash the string smh
2
u/Talc0n Sep 04 '26
Thing is there is a way to actually do it.
2
u/Denaton_ Sep 04 '26
No fall thru
1
u/americanov Sep 04 '26
Bro though he's on SO
1
u/zoniss Sep 04 '26
Pascal had native support for this
1
u/IUseClifford Sep 04 '26
Whose \#define is it anyway? C++, where the syntax is made up and nothing matters
1
u/pain_suffer Sep 04 '26
I'd have used enum+hashmap+switch but this is waaaaay cooler.
1
u/whackylabs Sep 04 '26
Looks like a lot of folks here are not familiar with Bourne Shell https://research.swtch.com/shmacro
1
u/caerphoto Sep 04 '26
Weaklings!
https://i.imgur.com/6rPeRJp.png
1
u/StudioYume Sep 05 '26
In C, just use bsearch if the strings are dynamic and just use a char pointer array indexed by an enum if they're constants.