gpt4 book ai didi

c - 使用属性 warn_unused_result 声明的警告 : ignoring return value of 'scanf' ,

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:03 24 4
gpt4 key购买 nike

#include <stdio.h>

int main() {
int t;
scanf("%d", &t);
printf("%d", t);
return 0;
}

我使用 ideone.com 编译上面的 C 代码并弹出以下警告:

prog.c: In function ‘main’:
prog.c:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result

谁能帮我理解这个警告?

最佳答案

你的 libc 的作者已经决定在大多数情况下不应忽略 scanf 的返回值,所以他们给它一个属性告诉编译器给你一个警告。

如果真的不需要返回值,那你就没事了。但是,通常最好检查它以确保您确实成功阅读了您认为自己所做的事情。

在你的情况下,代码可以这样写以避免警告(和一些输入错误):

#include <stdio.h>

int main() {
int t;
if (scanf("%d", &t) == 1) {
printf("%d", t);
} else {
printf("Failed to read integer.\n");
}
return 0;
}

关于c - 使用属性 warn_unused_result 声明的警告 : ignoring return value of 'scanf' ,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39293347/

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