Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]?

Tags:

g++

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

like image 261
sasha sami Avatar asked Jun 24 '13 12:06

sasha sami


1 Answers

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);
}
like image 151
perh Avatar answered Sep 22 '22 14:09

perh