Switch Statement Asm

closed account (o1vk4iN6)
I am using the MSVC compiler and I have a few questions about just how the assembly turns out. I've declared an enum:

1
2
3
enum MyEnum { 
  _A, _B, _C
};


and my code looks something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
MyEnum type;

switch(type){
  case _A:
    //do something
    break;
  case _B:
    //do something
    break;
  case _C:
    //do something
    break;
}


Although the way the assembly turns out it might as well be a giant if statement. As it goes and checks the value with each constant (0, 1, 2 etc..)

1
2
3
4
5
6
cmp type, _A
je 
cmp type, _B
je
cmp type, _C
je


I know my enum is going to be within a fixed range but its going to be have 100+ values so I'd rather it look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
MyEnum type;
void* jumps[] = {_A, _B, _C};

__asm jmp dword ptr [jumps + type * 4]

_A:
  //do something
_B:
  //do something
_C:
  //do something


I am probably going to end up just writing functions and make an array out of it but maybe someone has some better suggestions on what I should do.
Compilers generally use jump tables automatically when it is beneficial (i.e. when there are enough case statements). By default, g++ uses them when there are at least five cases.
Last edited on
Consider the application of polymorphic classes (they could be used in an array and perform independent actions).
Topic archived. No new replies allowed.