簡體   English   中英

為什么 GCC 只抱怨在給出 -pedantic 時將 unsigned int 參數與 %i 一起使用?

[英]Why does GCC only complain about an unsigned int argument being used with %i when -pedantic is given?

sscanf(3)說(強調我的):

i
匹配一個可選的有符號整數; next 指針必須是指向int的指針 如果整數以0x0X開頭,則以 16 0X讀取;如果以0開頭,則以 8 0X讀取,否則以 10 0X讀取。 僅使用對應於基數的字符。

然而,除非給出-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 會抱怨%ifloat * ,但不會抱怨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控制當參數類型僅在符號性與預期不同時是否引發警告。

gcc(1) 手冊頁

-Wformat-signedness
如果指定了 -Wformat,如果格式字符串需要一個無符號參數並且該參數是有符號的,則也會發出警告,反之亦然。

手冊頁沒有明確說明此標志包含在-pedantic ,( -Wpedantic )但它確實說:

但是,如果-Wpedantic-Wformat -Wpedantic使用,則會給出有關不在所選標准版本中的格式功能的警告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM