切换语句的更好替代方案

时间:2016-11-04 15:46:25

标签: c

我知道这已经讨论过,并且有多个答案。例如,请参阅Performance of array of functions over if and switch statements,但我想了解其他一些想法。

我有一个带有大switch语句的函数。这是26 case,每个都有“左”或“右”选项。此函数根据两个给定参数(planedirection)返回指针:

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:
    ...
  }
}

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

我一直在考虑一系列功能,但这也可能很乏味,我不确定它是不是最好的选择。我还不清楚如何正确地做到这一点。有什么想法吗?

4 个答案:

答案 0 :(得分:10)

您可以像这样创建一个查找表:

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

然后你的功能变得更加简单:

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

答案 1 :(得分:3)

如果你只是厌倦了打字,你可以使用预处理器,例如:

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

答案 2 :(得分:2)

不太确定,但也许你想要这个:

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];
}

需要添加更多测试,以确保planedirection在必需的范围内。

答案 3 :(得分:1)

您可以使用while与迭代器,如下所示:

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++;
  }
}

它没有经过优化,但相对于您的版本而言代码较少。

相关问题