Loose-Info.com
Last Update 2021/11/09
TOP - 各種テスト - gcc - 警告関連のオプション - -Wint-in-bool-context

-Wint-in-bool-context
if文の条件式のような真偽値が期待される箇所で、整数値が誤りを疑われるような使われ方をしている場合に警告を出力

テスト概要

オプション無し、-Wint-in-bool-context、-Wallの各オプションを使用した際の警告出力例

実行環境

GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1


コード例・出力内容中の表記

・実行例中の太字表記部分は、コマンドなどの入力された文字列を示します。
・「」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。

使用ファイル


sample.c
#include <stdio.h> int main(void) { int x = 2; /* if文の条件式に結果が整数定数となる条件評価式「?:」を使用 */ if (x > 1 ? 2 : 3) { printf("sample\n"); } /* if文の条件式に乗算を使用 */ if (x * 3) { printf("sample\n"); } /* if文の条件式に符合付き整数の左シフト演算を使用 */ if (x << 1) { printf("sample\n"); } return 0; }

動作テスト

オプション無しでコンパイルを実行
$ gcc sample.c 警告無し $

-Wint-in-bool-contextオプションを指定してコンパイルを実行
$ gcc -Wint-in-bool-context sample.c sample.c: In function ‘main’: sample.c:8:16: warning: ?: using integer constants in boolean context, the expression will always evaluate to ‘true’ [-Wint-in-bool-context] if (x > 1 ? 2 : 3) ~~~~~~~~~~^~~ sample.c:14:8: warning: ‘*’ in boolean context, suggest ‘&&’ instead [-Wint-in-bool-context] if (x * 3) ~~^~~ sample.c:20:8: warning: ‘<<’ in boolean context, did you mean ‘<’ ? [-Wint-in-bool-context] if (x << 1) ~~^~~~ $ ブーリアンコンテキストに関する各々の問題点の指摘が主となる警告

-Wallオプションを指定してコンパイルを実行
$ gcc -Wall sample.c sample.c: In function ‘main’: sample.c:8:16: warning: ?: using integer constants in boolean context, the expression will always evaluate to ‘true’ [-Wint-in-bool-context] if (x > 1 ? 2 : 3) ~~~~~~~~~~^~~ sample.c:14:8: warning: ‘*’ in boolean context, suggest ‘&&’ instead [-Wint-in-bool-context] if (x * 3) ~~^~~ sample.c:20:8: warning: ‘<<’ in boolean context, did you mean ‘<’ ? [-Wint-in-bool-context] if (x << 1) ~~^~~~ $ -Wint-in-bool-contextオプションは-Wallでも有効となる