Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better alternatives for switch statements

Tags:

c

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

I've got a function with a large switch statement. This is 26 case and each with a "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:
    ...
  }
}

with

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

I have been thinking on an array of functions, but this could also be tedious and I am not sure if it is the best option. Also it is not clear to me how to do it properly. Any ideas?

like image 628
Manolete Avatar asked Nov 04 '16 15:11

Manolete


People also ask

What can I use instead of a switch statement?

Luckily, JavaScript's object literals are a pretty good alternative for most switch statement use-cases I can think of. The idea is to define an object with a key for each case you would have in a switch statement. Then you can access its value directly using the expression you would pass to the switch statement.

What is the alternative option for switch statement in C?

The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable.

Why do people hate switch statements?

Last but not least, because a switch statement requires us to modify a lot of classes, it violates the Open-Closed Principle from the SOLID principles. To conclude, switch statement are bad because they are error-prone and they are not maintainable.

Should switch statements be avoided?

Therefore nested switch statements should be avoided. Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.


2 Answers

You can create a lookup table like this:

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

Then your function becomes much simpler:

double* getPointer(int plane, int direction) {
    if ((plane >= 0) && (plane < 26) && (direction >= 0) && (direction < 2)) {
        return pointers[plane][direction];
    } else {
        return NULL;
    }
}
like image 149
dbush Avatar answered Sep 20 '22 01:09

dbush


If you are just tired of typing, yu can use the preprocessor, e.g.:

#define PLZ(dir) if(!dir)return(p_YZ_L);else if(dir==1)return(p_YZ_R);else return 0;
like image 25
Paul Ogilvie Avatar answered Sep 18 '22 01:09

Paul Ogilvie