ignoring return value of ‘int scanf(const char*, …

2019-02-17 11:36发布

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 ??

标签: g++
2条回答
时光不老,我们不散
2楼-- · 2019-02-17 12:11

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);
}
查看更多
一夜七次
3楼-- · 2019-02-17 12:18

I took care of the warning by making an if statement that matches the number of arguments:

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    int i;
    long l;
    long long ll;
    char ch;
    float f;
    double d;

    //6 arguments expected
    if(scanf("%d %ld %lld %c %f %lf", &i, &l, &ll, &ch, &f, &d) == 6)
    {
        printf("%d\n", i);
        printf("%ld\n", l);
        printf("%lld\n", ll);
        printf("%c\n", ch);
        printf("%f\n", f);
        printf("%lf\n", d);
    }
    return 0;
}
查看更多
登录 后发表回答