-1

My Prog.c contains a simple switch case as follows:

switch (x)
{
    case 1:
        p=2;
        break;
    case 2:
        p=3;
        break;
    case 3:
        p=4;
        break;
    case 4:
        p=5;
        break;
    case 5:
        p=6;
        break;
    default:
        break;
}

I compiled this program with

gcc -g -v prog.c

and created objdump with

objdump -S -l a.out>dump_file

For the switch case statement, I have found that one indirect branch has been created (jmp *%eax).

But if I remove any one of the case statement, no indirect branch is created.

gcc version: 5.4.0

I could not understand why this is happening?

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
  • 1
    It might be useful to show us the output. Currently you could simply do `if (x>=1 && x<=5) p=x+1;` or jump to an address calculated from `x`. This does not work if you have a gap in the cases list. – Gerhardh Nov 22 '18 at 12:39
  • Compiler optimization decide to use indirect jumps than multiple comparisons. – EsmaeelE Nov 22 '18 at 12:40
  • maybe similar https://stackoverflow.com/a/11668346/7508077 – EsmaeelE Nov 22 '18 at 12:44

1 Answers1

0

This is happen because of Branch Tables. to avoid it compile with

gcc -g -v -fno-jump-tables SO.c

If you compile with jump tables [a feature in gcc compiler] size of dump_file is: 9,965 bytes

But without it size is: 11,493 bytes.

Jump tables helps to reduce object code size by optimize and relocate some jump instructions.

EsmaeelE
  • 2,331
  • 6
  • 22
  • 31