gpt4 book ai didi

c - 为什么 GCC 只提示在给出 -pedantic 时将 unsigned int 参数与 %i 一起使用?

转载 作者:行者123 更新时间:2023-12-04 10:29:56 25 4
gpt4 key购买 nike

sscanf(3) 说(强调我的):

i
Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used.



然而 GCC 并没有提示使用 unsigned int%i除非 -pedantic给出。这与我习惯的行为不同,其中 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) man page :

-Wformat-signedness
If -Wformat is specified, also warn if the format string requires an unsigned argument and the argument is signed and vice versa.



手册页没有明确说明此标志包含在 -pedantic 中。 , ( -Wpedantic ) 但它确实说:

However, if -Wpedantic is used with -Wformat, warnings are given about format features not in the selected standard version.

关于c - 为什么 GCC 只提示在给出 -pedantic 时将 unsigned int 参数与 %i 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60461745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com