prafulla said:
Hi all,
I don't have a copy of C standard at hand and so anyone of you can
help me. I have always wondered how switch statements are so efficient
in jumping to the right case (if any)? Can anybody point me to the
innards of it please?
Sorry if this is OT on clc and more relevant to comp.compilers. I am
confused here too.
This is really an implementation thing, not a language thing. How
a particular C compiler implements switch/case is irrelevent to the
C language itself.
That said...
There are numerous possibilities. Suppose, for example, that your
cases are 0, 1, 2, 3, 4, and 5. The compiler could generate a jump
table (after bounds checking) to each of the 6 possibilities, and
jump directly to the appropriate case. Another possibility, if the
cases are too disparate for a jump table, would be to generate a
binary search through the values. (ie: if less than the median
value, jump to A, else to B. Within A and B, each repeats the
median comparison, until you end up at a simple "is it this value,
and if not, jump to the default case".) You might even combine
these methods, if you have clusters of values within a disparate
group. (ie: 0, 1, 2, 3, 50, 51, 52, 99)
Of course, there's nothing stopping the compiler from generating
the equivalent of a bunch of if/else tests in the order in which
you code the cases.
If you have a specific compiler in mind, see if there is a groups
specifically for that compiler. Otherwise, comp.compilers would be
a good place for general questions regarding possible methods of
optimizing switch/case statements.
--
+---------+----------------------------------+-----------------------------+
| Kenneth | kenbrody at spamcop.net | "The opinions expressed |
| J. |
http://www.hvcomputer.com | herein are not necessarily |
| Brody |
http://www.fptech.com | those of fP Technologies." |
+---------+----------------------------------+-----------------------------+