5

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

mraron
  • 2,411
  • 18
  • 27
sasha sami
  • 525
  • 1
  • 10
  • 24

2 Answers2

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);
}
perh
  • 1,668
  • 11
  • 14
  • so how do I remove this warning because till date all the C programs I wrote I never checked the return value of scanf!!! Also what is this optimisation parameter can you throw some light? – sasha sami Jun 24 '13 at 12:12
  • Well, not checking means that the program will return the wrong value if either of the variables are not set by the sscanf (using uninitialized values). It is just a warning, not an error. As for it not being shown when not using (at least) -O due to a lack of analytics performed by the compiler -- that is just how it is. – perh Jun 24 '13 at 12:27
  • The fact that you never checked the return value of scanf before does not mean that it is a good idea to not check it. Try running 'echo 1 | your_program' to see what I mean, since 'b' will not be initialized a random value from the stack will be used instead. – perh Jun 24 '13 at 12:56
0

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;
}
user2926999
  • 393
  • 1
  • 3
  • 11