To implement a binary search for switch blocks, the compiler must inter-
nally represent the switch block as a tree. The idea is that instead of comparing
the provided value against each one of the possible cases in runtime, the com-
piler generates code that first checks whether the provided value is within the
first or second group. The compiler then jumps to another code section that
checks the value against the values accepted within the smaller subgroup. This
process continues until the correct item is found or until the conditional block
is exited (if no case block is found for the value being searched).
Let’s take a look at a common switchblock implemented in C and observe
how it is transformed into a tree by the compiler.
switch (Value)
{
case 120:
Code...
break;
case 140:
Code...
break;
case 501:
Code...
break;
case 1001:
Code...
break;
case 1100:
Code...
break;
case 1400:
Code...
break;
case 2000:
Code...
break;
case 3400:
Code...
break;
case 4100:
Code...
break;
};
502 Appendix A
21_574817 appa.qxd 3/16/05 8:54 PM Page 502