While I'm trying to disassemble my own C code I am stuck in a problem of not understanding how this Switch statement is implemented in assembly code. Can anyone please help to figure it out? This the switch assembly. Couldn't understand why so many registers are being used plus at the last line it's written "jmp dword ptr [eax4+0A110E8h]". Is this eax4 necessary for switch in assembly or did by the disassembler on its own? enter image description here

My C Code:

main() {
  int a;
  printf("Please enter a no between 1 and 5: ");
  scanf("%d", & a);
  switch (a) {
  case 1:
    printf("You chose One");
  case 2:
    printf("You chose Two");
  case 3:
    printf("You chose Three");
  case 4:
    printf("You chose Four");
  case 5:
    printf("You chose Five.");
    printf("Invalid Choice. Enter a no between 1 and 5");
  • All run-time checks are off which leads to compiler-generated code. – Ramesses II Feb 7 at 16:29

This is compiled to simple jump-table. Firstly it subtracts 1 from the a variable, so now your switch-case is for values in range <0;4> inclusive (instead of <1;5>). Next it checks if a is > 4, if so it jumps to the default label at 0A1109F. Note that the JA instruction is for the unsigned values, so it will jump to the default label in case if your value of a is negative.

Now the magic happens. It jumps to the address inside jump-table, the jump-table is 5 elements long (because there are 5 cases in your switch), and each element is 4 bytes long (because you compiled it for 32 bit architecture, and the sizeof pointer is 32 bits there, that's why it's eax*4). The jump-table starts at 0A110E8.

So if you dereference pointer at 0A110E8 you will get the address of "You chose one" block. Because for this case eax=0(it was decremented just moment ago), and [eax*4+0A110E8] = [0A110E8] now.

If you type 2 to the stdin, then eax=1, so [eax*4+0A110E8] = [1*4+0A110E8] = [0A110EC]. Now you can dereference the pointer 0A110EC and you will get the address of the second switch block, the address where the JMP instruction will redirect program flow in this case. The same rule applies for all the blocks.

  • and because of your magic, I understood it. Thanks, Brother! :D – Ramesses II Feb 8 at 17:53

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.