c c++ gcc if-statement switch-statement

How Switch case Statement Implemented or works internally?

I read somewhere that the switch statement uses “Binary Search” or some sorting techniques to exactly choose the correct case and this increases its performance compared to else-if ladder.

And also if we give the case in order does the switch work faster? is it so? Can you add your valuable suggestions on this?

We discussed here about the same and planned to post as a question.

It’s actually up to the compiler how a switch statement is realized in code.

However, my understanding is that when it’s suitable (that is, relatively dense cases), a jump table is used.

That would mean that something like:

switch(i) {
case 0: doZero(); break;
case 1: doOne();
case 2: doTwo(); break;
default: doDefault();

Would end up getting compiled to something like (horrible pseudo-assembler, but it should be clear, I hope).

load i into REG
compare REG to 2
if greater, jmp to DEFAULT
compare REG to 0
if less jmp to DEFAULT
jmp to table[REG]
data table
end data
ZERO: call doZero
jmp END
ONE: call doOne
TWO: call doTwo
jmp END
DEFAULT: call doDefault

If that’s not the case, there are other possible implementations that allow for some extent of “better than a a sequence of conditionals”.