From what I’ve read from various answers to similar questions, switch cases are compiled differently under some circumstances.
I have a few scenarios in mind but I’m not sure how they will compile.
Scenario 1
A switch case which takes an enum value. The cases range from 0 – 99 and are ordered.
Scenario 2
A switch case which takes an enum value. The cases range from lets say, 0 – 30, 50 – 80, 100 – 150. Unordered. Will this compile differently from the scenario above?
Basically I’d like to know how the switch cases in the scenarios will be compiled and if any differences exist between the two scenarios. Thanks!
edit: I should have mentioned that one of my biggest concerns is how many checks it would take to match the case. If statements are linear so for scenario one, if it was an if-else-if it would take at most 100 checks, unless I am mistaken. But how is this handled with switch-cases? What kind of optimizations does the compiler make?
There is no way to tell in general. The C++ standard makes hardly any assumption about the code which is generated. This means the compiler is free to almost (yes, there are exceptions) re-order you code, as long as the semantics stays the same. Optimisation was often called “the black magic of compiler construction” when I took courses in that topic.
Having this in mind, your compiler could spew out the same or different code. It may spit out the same code for some optimisation levels and completely different code for others. It may completely depend on the code you are using in the
caseblocks themselves. If you have the same code at two points, it might just optimize it to use that code once, or it might not.The only way to know what will happen is to look at the output of a compiler with certain fixed flags and see what happens. And once you found out what happens, do not rely on it, it might change in the next version of the compiler.
If you are programming always keep to the guarantees the language standard gives you and never assume anything beyond that.