忽略属性warn_unused_result [-Wunused-result]声明的'int scanf(const char *,...)'的返回值? [英] ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]?
问题描述
当我编译如下程序时:
g ++ -O2 -s -static 2.cpp
它给了我警告忽略返回值'int scanf(const char *,...)',声明属性为warn_unused_result [-Wunused-result]
。
但是当我删除 -02
来自复制语句不显示警告。
我的 2.cpp
程式:
#include >
int main()
{
int a,b;
scanf(%d%d,& a,& b);
printf(%d \ n,a + b);
返回0;
}
这个警告的含义是什么?是 -O2的含义
??
这意味着你不要检查scanf的返回值。
它可能很好地返回1(仅设置a)或0(不设置a和b)。
编译时未显示优化时未显示的原因是,除非启用优化,否则需要分析才能看到此内容。 -O2启用优化 - http://gcc.gnu.org/onlinedocs/gcc /Optimize-Options.html 。
只要检查返回值,就会删除警告,并使程序以可预测的方式运行,如果它没有收到两个数字:
if(scanf(%d%d,& a,& b)!= 2)
{
//做某事,比如..
fprintf(stderr,期望至少有两个数字作为输入\ n);
exit(1);
}
When I compiled the following program like:
g++ -O2 -s -static 2.cpp
it gave me the warning ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
.
But when I remove -02
from copiling statement no warning is shown.
My 2.cpp
program:
#include<stdio.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",a+b);
return 0;
}
What is the meaning of this warning and what is the meaning of -O2
??
It means that you do not check the return value of scanf.
It might very well return 1 (only a is set) or 0 (neither a nor b is set).
The reason that it is not shown when compiled without optimization is that the analytics needed to see this is not done unless optimization is enabled. -O2 enables the optimizations - http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html.
Simply checking the return value will remove the warning and make the program behave in a predicable way if it does not receive two numbers:
if( scanf( "%d%d", &a, &b ) != 2 )
{
// do something, like..
fprintf( stderr, "Expected at least two numbers as input\n");
exit(1);
}
这篇关于忽略属性warn_unused_result [-Wunused-result]声明的'int scanf(const char *,...)'的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!