How the switch statement works

How does the switch statement immediately get to the right place in memory? With nested if-statements, it should perform comparisons with each of them, but using the switch statement, it goes directly to the correct case. How is this implemented?

+6
source share
1 answer

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.

+15
source

Source: https://habr.com/ru/post/1014859/


All Articles