![](/img/trans.png)
[英]Why does coverity complain when using calloc with unsigned int
[英]Why does GCC only complain about an unsigned int argument being used with %i when -pedantic is given?
sscanf(3)
說(強調我的):
i
匹配一個可選的有符號整數; next 指針必須是指向int
的指針。 如果整數以0x
或0X
開頭,則以 160X
讀取;如果以0
開頭,則以 80X
讀取,否則以 100X
讀取。 僅使用對應於基數的字符。
然而,除非給出-pedantic
否則 GCC 不會抱怨使用unsigned int
和%i
。 這與我習慣的行為不同,其中 GCC 會警告任何不匹配的類型和格式字符串。
為什么這種組合表現不同?
鑒於此警告未包含在常見的-Wall
警告集中,是否可以將unsigned int
傳遞給%i
?
示例程序:
#include <stdio.h>
int main(void)
{
int i;
unsigned int u;
float f;
scanf("%i", &i);
scanf("%i", &u);
scanf("%i", &f);
return 0;
}
如果沒有-pedantic
,GCC 會抱怨%i
和float *
,但不會抱怨unsigned int *
:
$ gcc -Wall -Wextra scanf_i.c
scanf_i.c: In function ‘main’:
scanf_i.c:11:13: warning: format ‘%i’ expects argument of type ‘int *’, but argument 2 has type ‘float *’ [-Wformat=]
scanf("%i", &f);
~^ ~~
%e
使用-pedantic
,GCC 會抱怨兩者:使用-pedantic
輸出:
$ gcc -Wall -Wextra -pedantic scanf_i.c
scanf_i.c: In function ‘main’:
scanf_i.c:10:13: warning: format ‘%i’ expects argument of type ‘int *’, but argument 2 has type ‘unsigned int *’ [-Wformat=]
scanf("%i", &u);
~^ ~~
%i
scanf_i.c:11:13: warning: format ‘%i’ expects argument of type ‘int *’, but argument 2 has type ‘float *’ [-Wformat=]
scanf("%i", &f);
~^ ~~
%e
海灣合作委員會版本:
$ gcc --version
gcc (Debian 8.3.0-6) 8.3.0
-Wformat-signedness
控制當參數類型僅在符號性與預期不同時是否引發警告。
-Wformat-signedness
如果指定了 -Wformat,如果格式字符串需要一個無符號參數並且該參數是有符號的,則也會發出警告,反之亦然。
手冊頁沒有明確說明此標志包含在-pedantic
,( -Wpedantic
)但它確實說:
但是,如果
-Wpedantic
與-Wformat
-Wpedantic
使用,則會給出有關不在所選標准版本中的格式功能的警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.