C Programming – Searching Algorithm Used in Switch Statement

cswitch statement

What is the searching algorithm used in switch statement in C language?

If the cases are not in order still it searches proper case which means it is not a binary search algorithm, can anybody explain?

Best Answer

Several options:

  1. the naive method would be an if else cascade (slow)

  2. the compiler can sort the cases behind the scene and then do a binary search (good for disjoint cases)

  3. a jump table; only good for sequential cases but very fast.

For string-based switches there is the option of the prefix Trie, a sorted table that can be binary searched or the strings are hashed and used for the cases of a switch against the hash of the input string with a double check in each case.