Last Update 2021/10/07
-Wdeclaration-after-statement
ブロック内でステートメントの後に宣言が記述されている場合に警告を出力
テスト概要
オプション無し、-Wdeclaration-after-statement、-std=c90の各オプションを使用した際の警告出力例
実行環境
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 i;
int n1 = 1;
printf("%d\n", n1);
for (i=0; i<3; i++)
{
int j1 = i + 3;
printf("%d\n", j1);
/* forブロック内でステートメント出現後の宣言 */
int j2 = j1 + 3;
printf("%d\n", j2);
}
/* ブロック内でステートメント出現後の宣言 */
int n2 = n1 + 1;
printf("%d\n", n2);
return 0;
}
動作テスト
オプション無しでコンパイルを実行
$ gcc sample.c エラー・警告無し
$
-Wdeclaration-after-statementオプションを指定してコンパイルを実行
$ gcc -Wdeclaration-after-statement sample.c
sample.c: In function ‘main’:
sample.c:15:3: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
int j2 = j1 + 3;
^~~
sample.c:20:2: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
int n2 = n1 + 1;
^~~
$ ISO C90での、宣言とコードの混在禁止についての警告
-std=c90オプションを指定してコンパイルを実行
$ gcc -std=c90 sample.c エラー・警告無し
$ GCCではデフォルトで許可