Loose-Info.com
Last Update 2021/10/10
TOP - 各種テスト - gcc - 警告関連のオプション - -Wpointer-compare

-Wpointer-compare
ポインタがヌル文字定数('\0')と比較された場合に警告を出力

テスト概要

-Wpointer-compareオプションの使用、およびオプション無しの場合の警告出力例

実行環境

GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1


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

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

使用ファイル


sample.c
#include <stdio.h> int main(void) { char c = 'a'; char *pc = &c; if (pc == '\0') { printf("%d\n", *pc); } if (*pc == '\0') { printf("%d\n", *pc); } if (pc == 0) { printf("%d\n", *pc); } return 0; }

動作テスト

-Wpointer-compareオプションを使用してコンパイルを実行
$ gcc -Wpointer-compare sample.c sample.c: In function ‘main’: sample.c:8:9: warning: comparison between pointer and zero character constant [-Wpointer-compare] if (pc == '\0') ^~ sample.c:8:6: note: did you mean to dereference the pointer? if (pc == '\0') ^ $ ポインタとヌル文字定数('\0')との比較への警告

オプション無しでコンパイルを実行
$ gcc sample.c sample.c: In function ‘main’: sample.c:8:9: warning: comparison between pointer and zero character constant [-Wpointer-compare] if (pc == '\0') ^~ sample.c:8:6: note: did you mean to dereference the pointer? if (pc == '\0') ^ $ -Wpointer-compareオプションはデフォルトで有効となるため、指定した場合と同じ結果となる