【C言語】switch( bool式)を避けif文で単純に書こう(KISSの原則)

warning: switch condition has boolean value

警告:switch(条件式)がブール値を持つ
[-Wswitch-bool]

■1.switch(bool式)は避ける

#include    <stdio.h>
#include    <stdbool.h>

int f1(int x)
{
    switch(x < 0){  //ダメ:switch(真偽値)は避けましょう
    case    true:   return  1 ;
    case    false:  return  0  ;
    }
}

switch文は多分岐に適しているので
真か偽の2分岐しかないbool型の判定では
単純なif文を使いましょう。

■2.> と >> を間違えた例

#include    <stdio.h>
#include    <stdbool.h>
typedef unsigned int    U4;
int f2(U4 x)
{
    switch(x > 8) { //ダメ:> と >> を間違えた?
    case    0xFF:       return  1;
    case    0xFFFF:     return  2;
    case    0xFFFFFF:   return  3;    
    }
    return  4;
}

上記はプログラマが
x>> 8(シフト命令)と記述する所を
x> 8(比較命令)と間違えた例です。

■3.bool変数に無理やり3を設定

#include    <stdbool.h>
#include    <stdio.h>
int main(void)
{
    bool    b ;
    b = 3 ; 
    printf("b = %d\n",b) ;
    printf("sizeof(b) = %ld\n",sizeof(b));

    *(char *)&b = 3 ; 
    printf("b = %d\n",b) ;

    switch(b){
        case    true:   printf("sw:true\n");    break;
        case    false:  printf("sw:false\n");   break;
        default:        printf("sw:default\n"); break;
    }
    if(b == 0)          printf("if:0\n");
    else if(b == 1)     printf("if:1\n");
    else                printf("if:else\n");
}

bool変数に対して
*(char *)&b = 3 ; のような無理な代入を行うと
処理系依存とか未定義動作となるので止めましょう。

上記のコードでは 
gccコンパイラと 
clangコンパイラ で動作が異なります。

参考:

KISSの原則

https://ja.wikipedia.org/wiki/KISS%E3%81%AE%E5%8E%9F%E5%89%87