Good morning, here's your friendly "Code-Myth-Buster".
The claim is that compilers turn lengthy switch statements into lookup tables automatically.
Test 1: A switch-statement with 0-n case numbering.
Code: Select all
int main( int argc, char * argv[] )
{
switch ( argc )
{
case 0:
return 254;
case 1:
return 125;
case 2:
return 42;
case 3:
return 23;
case 4:
return 7;
case 5:
return 1;
default:
return 0;
}
}
Compiled with gcc -O2, and disassembled with objdump:
Code: Select all
0000000000000000 <main>:
0: 31 c0 xor %eax,%eax
2: 83 ff 05 cmp $0x5,%edi
5: 77 0e ja 15 <main+0x15>
7: 89 f8 mov %edi,%eax
9: ff 24 c5 00 00 00 00 jmpq *0x0(,%rax,8)
10: b8 07 00 00 00 mov $0x7,%eax
15: f3 c3 repz retq
17: b8 fe 00 00 00 mov $0xfe,%eax
1c: c3 retq
1d: b8 01 00 00 00 mov $0x1,%eax
22: c3 retq
23: b8 17 00 00 00 mov $0x17,%eax
28: c3 retq
29: b8 2a 00 00 00 mov $0x2a,%eax
2e: 66 90 xchg %ax,%ax
30: c3 retq
31: b8 7d 00 00 00 mov $0x7d,%eax
36: c3 retq
Test 2: A switch-statement with random numbering.
Code: Select all
int main( int argc, char * argv[] )
{
switch ( argc )
{
case 5:
return 254;
case 18:
return 125;
case 22:
return 42;
case 31:
return 23;
case 34:
return 7;
case 51:
return 1;
default:
return 0;
}
}
Compiled with gcc -O2, and disassembled with objdump:
Code: Select all
0000000000000000 <main>:
0: 8d 47 fb lea -0x5(%rdi),%eax
3: 83 f8 2e cmp $0x2e,%eax
6: 77 09 ja 11 <main+0x11>
8: 89 c0 mov %eax,%eax
a: ff 24 c5 00 00 00 00 jmpq *0x0(,%rax,8)
11: 31 c0 xor %eax,%eax
13: c3 retq
14: b8 fe 00 00 00 mov $0xfe,%eax
19: c3 retq
1a: b8 01 00 00 00 mov $0x1,%eax
1f: 90 nop
20: c3 retq
21: b8 07 00 00 00 mov $0x7,%eax
26: c3 retq
27: b8 17 00 00 00 mov $0x17,%eax
2c: 0f 1f 40 00 nopl 0x0(%rax)
30: c3 retq
31: b8 2a 00 00 00 mov $0x2a,%eax
36: c3 retq
37: b8 7d 00 00 00 mov $0x7d,%eax
3c: 0f 1f 40 00 nopl 0x0(%rax)
40: c3 retq
And now the price question: Given 256 possible values, which code is
better readable and
better maintainable: A 515-line switch block, or a 10-line lookup table logic?