0

While I was disassembling my own C code for practice I saw an interesting point which I want to share with you guys and needs to know the answer as I always get from here. Now, the interesting point is when I'm disassembling for switch cases when I'm making cases for one-digit numbers like 1, 2, etc. the disassembler is using jump-table for them but when I'm making cases for digits with zeroes like 10, 200, 300, etc. I'm seeing the disassembly with no jump-table but only a bunch of CMPs and JCCs one after another. I can't figure out why it's doing this but it's very interesting, can anyone tell me why? My two codes...

int number=5;
switch (number) {
case 1:
case 2:
case 3:
 printf("One, Two, or Three.\n");
 break;
case 4:
case 5:
case 6:
 printf("Four, Five, or Six.\n");
 break;
default:
 printf("Greater than Six.\n");}}

and disassembly for it...

enter image description here

now the code but with cases with numbers like 200, etc.

int number=500;
switch (number) {
case 100:
case 200:
case 300:
 printf("100, 200, or 300.\n");
 break;
case 400:
case 500:
case 600:
 printf("400, 500, or 600.\n");
 break;
default:
 printf("Greater than Six.\n");}}

and disassembly for it...

enter image description here

it seems so chatty. Thanks in advance!

2
  • 1
    You mean “the compiler is” (doing this or that). The disassembler is just showing you the result. – Igor Skochinsky Feb 10 at 12:24
  • Whoops! Got it! – Ramesses II Feb 10 at 12:44
0

This topic has been explored by Rolf Rolles in this OpenRCE article (reposted here).

Briefly, when the cases are close together, the compiler can use the switch variable to index a jump table. However, when cases are further apart, it would have to generate a huge table with many empty cases which would blow up the binary size. Although the sequence of cmp and conditional jumps may look silly and verbose, in most cases it's not noticeably slower and certainly uses less space (which would further improve performance by fitting into the instruction cache).

At high optimization levels, advanced compilers can even split a switch into several small ones that do have cases grouped closely and then use a couple of comparisons to decide which of them to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.