#include <stdio.h>
int main() {
switch ( 4 ) {
case 1: printf( "case1\n" ); break;
case 2: printf( "case2\n" ); break;
case 3: printf( "case3\n" ); break;
case 4: printf( "case4\n" ); break;
case 5: printf( "case5\n" ); break;
case 6: printf( "case6\n" ); break;
}
}
Is translated into this assembler
The salient part of which is
; switch ( 4 ) {
;
@1:
mov eax,4 // Load the selector expression (4)
cmp eax,6 // Test if its outside the range of options (6)
ja short @2 // If it is, jump to the default
/*
Otherwise, add the value * the size of the lookup table
entries (4bytes) and add it to the base address of the
dispatch table, then jump to the address help at that
location in the table.
*/
jmp dword ptr [@10+4*eax]
@10:
dd @2
dd @9
dd @8
dd @7
dd @6
dd @5
dd @4
;
; case 1: printf( "case1\n" ); break;
;
@9:
Originally, the offsets were byte offsets and the table size had a maximum of 255. These days, the table entries are absolute 32-bit addresses and the table size can theoretically be 2 GB in size. In all cases, it is very fast.
The interesting part is coding the switch expression so that it converts your range of possible matches to an integer. String lookups can be index using str(i)(n)cmp() quite easily, but I've had to code some more esoteric versions in the past.
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
Hooray!
|