Last Update 2021/11/03
-Wlogical-not-parentheses
比較の左辺オペランドに論理否定が使用されている場合に警告を出力
テスト概要
オプション無し、-Wlogical-not-parentheses、-Wallの各オプションを使用した際の警告出力例
実行環境
GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1
GNU C Library 2.28
GNU Binutils 2.31.1
コード例・出力内容中の表記
・実行例中の太字表記部分は、コマンドなどの入力された文字列を示します。
・「︙」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。
・「︙」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。
使用ファイル
sample.c
#include <stdio.h>
int main(void)
{
int a = 7;
/* 比較の左辺オペランドに論理否定をカッコ無しで記述 */
if (!a < 1)
{
printf("!a = %d\n!a < 1 = %d\n", !a, (!a < 1));
}
/* 比較の左辺オペランドに論理否定をカッコ付きで記述 */
if ((!a) < 1)
{
printf("(!a) = %d\n(!a) < 1 = %d\n", (!a), ((!a) < 1));
}
/* 比較の右辺オペランドに真偽値を記述 */
if (!a < (a != 0))
{
printf("!a = %d\n!a < (a != 0) = %d\n", !a, (!a < (a != 0)));
}
return 0;
}
動作テスト
オプション無しでコンパイルを実行
$ gcc sample.c 警告無し
$
-Wlogical-not-parenthesesオプションを指定してコンパイルを実行
$ gcc -Wlogical-not-parentheses sample.c
sample.c: In function ‘main’:
sample.c:8:9: warning: logical not is only applied to the left hand side of comparison [-Wlogical-not-parentheses]
if (!a < 1)
^
sample.c:8:6: note: add parentheses around left hand side expression to silence this warning
if (!a < 1)
^~
( )
sample.c:10:44: warning: logical not is only applied to the left hand side of comparison [-Wlogical-not-parentheses]
printf("!a = %d\n!a < 1 = %d\n", !a, (!a < 1));
^
sample.c:10:41: note: add parentheses around left hand side expression to silence this warning
printf("!a = %d\n!a < 1 = %d\n", !a, (!a < 1));
^~
( )
$ 論理否定は比較の左辺オペランドにのみ適用される事を伝える警告と、
左辺オペランドをカッコで囲うことで警告を回避できる事に関する注釈
比較の右辺オペランドが真偽値の場合は警告は出力されない
-Wallオプションを指定してコンパイルを実行
$ gcc -Wall sample.c
sample.c: In function ‘main’:
sample.c:8:9: warning: logical not is only applied to the left hand side of comparison [-Wlogical-not-parentheses]
if (!a < 1)
^
sample.c:8:6: note: add parentheses around left hand side expression to silence this warning
if (!a < 1)
^~
( )
sample.c:10:44: warning: logical not is only applied to the left hand side of comparison [-Wlogical-not-parentheses]
printf("!a = %d\n!a < 1 = %d\n", !a, (!a < 1));
^
sample.c:10:41: note: add parentheses around left hand side expression to silence this warning
printf("!a = %d\n!a < 1 = %d\n", !a, (!a < 1));
^~
( )
$ -Wlogical-not-parenthesesオプションは-Wallでも有効となる