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?
1
Several options:
-
the naive method would be an if else cascade (slow)
-
the compiler can sort the cases behind the scene and then do a binary search (good for disjoint cases)
-
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.
2
Generally, switch statements are implemented as Jump Tables. There is no searching involved.
2