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?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
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.
Generally, switch statements are implemented as Jump Tables. There is no searching involved.