Best alternatives for switch statements

I know that this has already been discussed, and there are several answers to it. See Performance of an array of functions on if and switch statements , however I would like to get some other ideas.

I have a function with a big switch . This is a 26 case and each with the left or right option. This function returns a pointer based on two given parameters ( plane and direction ):

 double* getPointer(int plane, int direction) { switch (plane) { case 0: if (direction == 0) return p_YZ_L; // Left else if (dir == 1) return p_YZ_R; //Right else { return 0; } break; ... case 25: ... } } 

from

 planes -> [0-25] direction -> [0,1] 

I thought of a lot of features, but it can also be tedious, and I'm not sure if this is the best option. It is also not clear to me how to do this properly. Any ideas?

+6
source share
4 answers

You can create a lookup table as follows:

 double *pointers[26][2] = { { p_YZ_L, p_YZ_R }, ... }; 

Then your function will become much simpler:

 double* getPointer(int plane, int direction) { if ((plane >= 0) && (plane < 26) && (direction >= 0) && (direction < 2)) { return pointers[plane][direction]; } else { return NULL; } } 
+9
source

If you're just tired of input, yu might use a preprocessor, like this:

 #define PLZ(dir) if(!dir)return(p_YZ_L);else if(dir==1)return(p_YZ_R);else return 0; 
+3
source

Not quite sure, but maybe you need this:

 struct { double dir[2]; } directions[26] = { { p_YZ_L, p_YZ_R}, { ..., ... }, // 25 pairs of options here ... }; double* getPointer(int plane, int direction) { return &directions[plane].dir[direction]; } 

Additional tests must be added to ensure that plane and direction are within the required boundaries.

+2
source

You can use while with an iterator as follows:

 double* getPointer(int plane, int direction){ int i=0; while (i<26){ if (plane == i){ if (direction == 0) return p_YZ_L; //Left else if(dir==1) return p_YZ_R; //Right else return 0; } i++; } } 

It is not optimized, but it is less code relative to your version.

+1
source

Source: https://habr.com/ru/post/1012042/


All Articles