There are many different ways to compile the switch
into machine code. Here are a few:
The compiler can run a series of tests that are not so inefficient, since just log 2 (N) tests are enough to send a value among N possible cases.
The compiler can create a table of values ββand jump addresses, which, in turn, will be used by a common search code (linear or dichotomous, similar to bsearch()
) and, finally, go to the corresponding location.
If the case values ββare sufficiently dense, the compiler can generate a table of jump addresses and a code that checks if the switch value is within the range that covers all case values ββand jumps directly to the corresponding address. This is probably the implementation closest to your description: but with the switch statement, it goes directly to the correct case.
Depending on the specific capabilities of the target CPU, the compiler options, and the number and distribution of case values, the compiler can use one of the above approaches or a combination of them or even some other methods.
Compiler designers are working hard to improve heuristics for these options. Take a look at the build or use an online tool like Godbolt Compiler Explorer to see various code generation options.
source share