【C言語】
多分岐にはswitch文を使おう!
else if文をズラズラ並べない

(style): else if Vs switch


■この記事の概要

この記事では、
C言語におけるifとswitchの使い分けを比較し、
else ifを多用した非効率なコードの
問題点を指摘しています。
特に多分岐処理において、
switch文の方がコンパイル時にエラーを検出しやすく、
より効率的なコードを生成できることを
解説しています。


■else ifをズラズラ並べた例(非推奨)

#include <stdio.h>
char *風林火山(int x) {
    if(x == 1) 
    {
        return  "風";
    } else 
    if(x == 2)
    {
        return  "林";
    } else 
    if(x == 3)
    {
        return  "火";
    } else 
    if(x == 1)
    {//NG 4の間違い
        return  "山";
    }
    return  "バグ" ;
}
int main(void){
    printf("%s\n",風林火山(4));
}
#include <stdio.h>
char *風林火山(int x) {
    switch(x){ 
    case 1: return  "風";
    case 2: return  "林";
    case 3: return  "火";
    case 1: return  "山";//case 4の間違い
    }
    return  "バグ" ;
}
int main(void){
    printf("%s\n",風林火山(4));
}

if文は
if(x == 1)が重複していますが、
コンパイルエラーは出ないので
間違いに気付きにくいです。

switch文はを
コンパイルエラーになるので
簡単に重複を防げます。

if/elseをずらずら並べるより
switchは
おそらく効率の良いコードが生成されます。


■||演算子をズラズラ並べ例(非推奨)

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

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

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

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

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

参考:

C-FAQ20.16:Which is more efficient, a switch statement or an if/else chain?