><sa*****@yahoo.co.inwrote in message
>news:11**********************@p77g2000hsh.googleg roups.com...
>I wanted to know as to how a switch case like the following one is
converted into a jump table by the compiler, assuming that it does ...
[code snipped, but the range for the selector was 4..1000]
In article <46***********************@free.teranews.com>
Stephen Sprunk <st*****@sprunk.orgwrote:
>I doubt a decent compiler would use a jump table for this; it's way too
sparse.
Yes, although as Richard Heathfield noted, one can apply a reduction
function first. (This complicates the code since each match must
then reject false hits.)
>Still, if it did, the asm would look something like this
pseudocode:
void *jumptable[1001] = { default, default, default, default, label4,
label56, label56, default, ... , default, label1000 };
Actually, more like:
static void *const __table[1000 - 4 + 1] =
{ &&__label4, &&__label56, &&__label56,
&&__label_default, ..., &&__label_default, &&__label1000 };
(using gcc's "&&label" syntax), and:
>/* insert your code to set i */
goto jumptable[i];
replace this "goto" with:
if (i >= 4 && i <= 1000) goto __table[i - 4];
goto __label_default;
or (closer to typical machine code):
if ((%t0 = i - 4) < 0) goto __label_default;
if (%t0 1000 - 4) goto __label_default;
goto __table[%t0];
(where %t0 is a "compiler's temporary values" machine register).
The specifics are quite machine-dependent, but in general, there
are two criteria for using a jump table: the "load factor" (or
"fill factor" or other similar name) has to be high enough, typically
at least 2/3 -- i.e., most of the table-slots must not be the
"default:" label, or if there is no default, the internally-generated
"end of switch" label (which is then used as the default) -- and
there must be some minimum number of target labels (typically at
least 3 to 5).
If the number of labels is very low, a simple compare/goto sequence
is usually best.
If the number of labels is high but the table is sparse, the compiler
should:
- break up the cases into contiguous sub-ranges
- use a hash system
- use a binary search
- use an interpolative search
and/or some combination of all of the above. For instance, if we
have cases 0, 1, 2, 3, 4, 6, 100, 9000, 9001, 9002, 9003, and 15000,
we might want machine code like:
if (i 100) {
if (i == 15000) goto __label_15000;
if (i < 9000 || i 9003) goto __label_default;
goto __table9000[i - 9000];
} else if (i == 100)
goto __label_100;
else if (i < 0 || i >= 6)
goto __label_default;
else
goto __table0[i - 0];
(I am not sure how often interpolative search would pay off.
Probably not often -- most cases where it would, would be
subsumed by a jump table.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.