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 communityWhat 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?
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.
case 1: foo; case 2: bar; break;
that can make some cases a bit more difficult to do.
goto endSwitch;
for each break.
Dec 12, 2014 at 20:03
Generally, switch statements are implemented as Jump Tables. There is no searching involved.