【C言語】
ifとswitchどっちが良い?
(switch vs else if)

(style): Expression is always false because ‘else if’ condition matches previous condition at line

(スタイル):8行目のelse ifは2行目で判定済みなので成立する事はない
[(style)multiCondition]


■1.else ifをズラズラ並べた失敗例

int f(int x) {
    if(x == 1) {
        return  1;
    } else if(x == 2){
        return  2;
    } else if(x == 3){
        return  3;
    } else if(x == 1){//NG 重複
        return  4;
    }
    return  -1;
}

switch文を使用するとこの重複は防げ
if/elseをずらずら並べるより
おそらく効率の良いコードが生成されます。


●switchを使った修正例1

int f(int x) {
    switch(x){
    case 1:     return  1;
    case 2:     return  2;
    case 3:     return  3;
    case 4:     return  4;
    default:  
        return  -1;
    }
}

■2.OR演算子をズラズラ並べた失敗例

(style) Same expression on both sides of ‘||’.

スタイル:’||’演算子の両辺同じ[(style)duplicateExpression]

int f1(int x)   {
    if( (x==1)  ||
        (x==1)  ||  //重複   
        (x==3)  ){
            return  1;
    }
    return  0;  
}

if文の重複はコンパイルエラーにならないので
間違いに気が付きません。


●switchを使った修正例2

int f2(int x)   {
    switch(x){
    case    1:  
    case    1://コンパイルエラーになる
    case    3:  
        return  1;
    }
    return  0;  
}

switch文caseの重複はコンパイルエラーになるので
間違いに気が付きます。

■3.まとめ:多分岐にはswitchを使おう!
else ifをズラズラ並べない

参考:

Which is more efficient, a switch statement or an if/else chain?