Compiler

Switch and Jump Table

how a switch case like the following one is
converted into a jump table by the compiler, assuming that it does:

switch(i)
{
case 4: 
...
printf("4");
break;
 
case 5:
case 6:
 
printf("56");
break;
 
case 1000: 
printf("1000");
break;
 
default: 
printf("default");
break;
}

I doubt a decent compiler would use a jump table for this; it's way too sparse. 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 };
 
/* insert your code to set i */
 
goto jumptable[i];
 
label4:
printf("4");
goto end;
label56:
printf("56");
goto end;
label1000:
printf("1000");
goto end;
default:
printf("default");
end:
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License