Last Update 2021/10/07
-Wshadow=オプション引数(-Wshadow)
宣言されている変数と同じ識別子で、内包されるスコープにおいて変数が宣言された際の隠ぺいの状況により警告を出力
テスト概要
オプション無し、-Wshadow、-Wshadow=globalの各オプションを使用した際の警告出力例
-Wshadow=localオプションを使用した際の警告出力例
-Wshadow=compatible-localオプションを使用した際の警告出力例
実行環境
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>
/* ファイルスコープで宣言された変数n */
int n = 1;
int main(void)
{
int i;
printf("%d\n", n);
/* 関数スコープで宣言された変数n */
int n = 0;
/* 関数スコープで浮動小数点型で宣言された変数d */
double d = 1.23;
printf("%d %f\n", n, d);
for(i=0; i<3; i++)
{
/* ブロックスコープで宣言された変数n */
int n = i + 1;
/* ブロックスコープで整数型で宣言された変数d */
int d = i + 2;
printf("%d %d\n", n, d);
}
return 0;
}
オプション無し、-Wshadow、-Wshadow=globalの各オプションを使用した際の警告出力例
オプション無しでコンパイルを実行
$ gcc sample.c エラー・警告無し
$
-Wshadowオプションを指定してコンパイルを実行
着色部(青)は各警告出力についての解説
着色部(青)は各警告出力についての解説
$ gcc -Wshadow sample.c
sample.c: In function ‘main’:
sample.c:13:6: warning: declaration of ‘n’ shadows a global declaration [-Wshadow]
int n = 0; nの宣言がファイルスコープの宣言を隠ぺい
^
sample.c:4:5: note: shadowed declaration is here
int n = 1;
^
sample.c:23:7: warning: declaration of ‘n’ shadows a previous local [-Wshadow]
int n = i + 1; nの宣言が関数スコープの宣言を隠ぺい
^
sample.c:13:6: note: shadowed declaration is here
int n = 0;
^
sample.c:26:7: warning: declaration of ‘d’ shadows a previous local [-Wshadow]
int d = i + 2; dの宣言が関数スコープの宣言を隠ぺい
^
sample.c:16:9: note: shadowed declaration is here
double d = 1.23;
^
$ グローバルな宣言を含む変数の隠ぺいに関する警告
-Wshadow=localオプションを使用した際の警告出力例
-Wshadowオプションを指定してコンパイルを実行
着色部(青)は各警告出力についての解説
着色部(青)は各警告出力についての解説
$ gcc -Wshadow=local sample.c
sample.c: In function ‘main’:
sample.c:23:7: warning: declaration of ‘n’ shadows a previous local [-Wshadow=compatible-local]
int n = i + 1; nの宣言が関数スコープの宣言を隠ぺい
^
sample.c:13:6: note: shadowed declaration is here
int n = 0;
^
sample.c:26:7: warning: declaration of ‘d’ shadows a previous local [-Wshadow=local]
int d = i + 2; dの宣言が関数スコープの宣言を隠ぺい
^
sample.c:16:9: note: shadowed declaration is here
double d = 1.23;
^
$ 関数スコープ内(ローカル)で宣言された変数の隠ぺいに関する警告
オプション引数「local」に「compatible-local」が含まれるため同時に出力される
-Wshadow=compatible-localオプションを使用した際の警告出力例
-Wshadow=compatible-localオプションを指定してコンパイルを実行
着色部(青)は各警告出力についての解説
着色部(青)は各警告出力についての解説
$ gcc -Wshadow=compatible-local sample.c
sample.c: In function ‘main’:
sample.c:23:7: warning: declaration of ‘n’ shadows a previous local [-Wshadow=compatible-local]
int n = i + 1; nの宣言が関数スコープの宣言を隠ぺい
^
sample.c:13:6: note: shadowed declaration is here
int n = 0;
^
$ 関数スコープ内(ローカル)で宣言された互換性の有る型の変数の隠ぺいに関する警告
上記の例では変数dは浮動小数点型(関数内)と整数型(ブロック内)で互換性が無いため、警告の出力は無し