switch statement

how does a compiler translate a switch statement. I must write very optimized code.

Here a little piece auf code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
myfunction() {

  int i = ....
  switch(i) {
    case 0:
    ...
    break;
    case 1:
    ...
    break;

    ...
    ...
  } 

}


Does the compiler translates this like if (case1) then... else if (case2) then..
i want to avoid this because the code must be very fast and there are to many cases in the switch statement.

I had the idea to work with GOTO saving the jump postions in an array at the index of case X. Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

int* jumpPointers
jumpPointers[0] = reinterpret_cast<int*>(&&label0); // Is it right to use int* to save a pointer?? 4 bytes ??
jumpPointers[1] = reinterpret_cast<int*>(&&label1);

myfunction() {

  int i = ....
  goto reinterpret_cast<void*>(jumpPointers[i]);

  label0:
  ...
  goto labelFinished;
  label1:
  ...
  goto labelFinished;

  ...
  ...
 
  labelFinished

}


This would be much faster if it works but have a problem using the && operator for GOTO. Its not the logical and!!! Does anybody know if the msvc 2008 compiler supports this feature and how to activate it.

Does anyone knows an other way to avoid the switch statement.

Thx for any help.
The standard does not mandate how any part of C++ gets translated to machine code. Having said that, a good optimizing compiler may attempt to compile a switch statement into a jump table similar to what you are trying to do provided that a) you order your cases in numerical order starting with 0 or 1; and b) you do not skip any numbers (ie, if you have case 0 and case 10, then you must also have cases 1 through 9.)

Having said that, you cannot rely on the compiler to do this. Your best alternative would be to use function pointers instead of labels.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
typedef void (*fn)();

void myfunction() {
    static fn    funcs[ 5 ];
    static bool once = false;
    if( !once ) {
        funcs[ 0 ] = &case0_handler;  // This is a function you define elsewhere
        funcs[ 1 ] = &case1_handler;  // This is a function you define elsewhere
        // etc.
        once = true;
    }

    fn[ 3 ]();  // Call function
}

Thx! i will try to find out how the vs2008 compiler translates a swith statement.
Function calls are not a good alternate cause they produce some overhead
Topic archived. No new replies allowed.