Last Update 2021/06/05
-Wformat-signedness
フォーマット文字列とフォーマット引数の符号有無の指定に違いがある場合に警告を出力
テスト概要
-Wformat、-Wformat-signednessオプションを使用したコンパイル時の警告出力例
実行環境
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 n1 = -1;
unsigned int n2 = 1;
double f = 1.01;
/* フォーマット文字列の指定は符号無し、フォーマット引数は符号有り */
printf("n1 : %u\n", n1);
/* フォーマット文字列の指定は符号有り、フォーマット引数は符号無し */
printf("n2 : %d\n", n2);
/* フォーマット文字列とフォーマット引数が型違い */
printf("f : %d\n", f);
return 0;
}
動作テスト
-Wformat、-Wformat-signednessオプションを使用したコンパイル時の警告出力例
オプション無しで実行
$ gcc sample.c
$ エラー・警告無し
-Wformatオプションのみを指定して実行
$ gcc -Wformat sample.c
sample.c: In function ‘main’:
sample.c:16:15: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]
printf("f : %d\n", f); フォーマット文字列とフォーマット引数が型違いであるため警告発生
~^ ~
%f
$ 符号指定の有無に関する警告は出力されない
-Wformatと-Wformat-signednessオプションを指定して実行
$ gcc -Wformat -Wformat-signedness sample.c
sample.c: In function ‘main’:
sample.c:10:16: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int’ [-Wformat=]
printf("n1 : %u\n", n1); フォーマット文字列の指定は符号無し、フォーマット引数は符号有り
~^ ~~
%u
sample.c:13:16: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘unsigned int’ [-Wformat=]
printf("n2 : %d\n", n2); フォーマット文字列の指定は符号有り、フォーマット引数は符号無し
~^ ~~
%d
sample.c:16:15: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]
printf("f : %d\n", f); フォーマット文字列とフォーマット引数が型違い
~^ ~
%f
$ 符号指定の有無に関する警告も型違いと同じく[-Wformat=]として出力される
-Wformat無しで-Wformat-signednessオプションのみを指定して実行
$ gcc -Wformat-signedness sample.c
$ エラー・警告無し