【C言語】
論理演算子||と&&の使い方
~結果は0か1にしかならない~

warning: use of logical ‘||’ with constant operand

警告:論理演算子||に定数を使った
[-Wconstant-logical-operand]


この記事の概要

この記事では、C言語の論理演算子「||」に定数を用いる誤りを解説しています。
if(x == 'a' || 'A')のようなコード例を挙げ、意図しない動作や誤解を防ぐための適切な修正法を示します。


論理演算子【||】の間違った使い方

#include <stdio.h>
int main(void)
{
    puts("'b'を入力してね");
    
    int x = getchar();
    if(x == 'a' || 'A'){
        printf("Aに来ました=%c\n",x);
    } else 
    if(x == 'b' || 'B'){
        printf("Bに来ました=%c\n",x);
    } else {
        printf("Cに来ました=%c\n",x);    
    }
}

実行結果を予想して下さい⇨解答はこちら

このプログラムは何を入力しても
最初の論理演算子の右辺 【’A’ 】が非ゼロの定数なので
論理演算は必ず成立してしまいます。
if(x == ‘a’ || ‘A’){は誤りで
if(x == ‘a’ || x == ‘A’){が正解です。


warning: comparison of constant ‘2’ with boolean expression is always false

warning: result of comparison of constant 2 with boolean expression is always false
警告:定数 ‘2’ とboolean式の比較は常に偽
[-Wbool-compare]
[-Wtautological-constant-out-of-range-compare]


■論理演算子【&&】の間違った使い方

#include <stdio.h>
#include <stdint.h>

//論理演算
int logop(uint32_t x) {
    if ((x && 2) == 2) //★NG
        return  1;//ここには来ない
    return  0;
}
//ビット演算
int bitop(uint32_t x) {
    if ((x & 2) == 2) //OK 
        return  1;
    return  0;
}
int main(void){
    printf("論理演算  =%d\n",logop(2));
    printf("ビット演算=%d\n",bitop(2));
}

論理演算の結果は0か1にしかなりません。
したがって(x && 2)の結果は0か1にしかならないので
xの値にかかわらず
if((x && 2) == 2)が成立する事はありません。

■実行結果

 ./a.out 
論理演算  =0
ビット演算=1

■論理演算の結果は0か1にしかならない

【論理演算の結果は0か1にしかなりません。】
↑正解

【論理演算の結果は0か非ゼロになる。】
↑こう覚えてる人が結構多いですが微妙に間違いです。
非ゼロではなくて1です。

参考: C-FAQ9.2