I am trying to compile a C program using gcc with optimization enabled.
gcc [name] -lm
works fine, but as soon as I add -O3 it gives me this warning:
warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
What am I missing here?
Why does this warning depend on the optimization level? [from comment section]
The main reason is that there are certain analysis enabled by different optimization levels.
The absolute best way is to do as the compiler tells you. Not checking the return value of various functions is something that is the source of many bugs. Just do something like this:
if(scanf("%d%d", &x, &y) != 2) { /* Handle error * }
and the warning will disappear.
If you instead decide that you know better than the compiler and simply want it to shut up, then you can also do as the warning tells you, even if it's not so obvious how it is done. Use this code:
#pragma GCC diagnostic warning "-Wunused-result"
That method can be used for a lot of warnings. In this particular case, it's however more conventional to cast the result:
(void)scanf( ...
but that does not always work.
Do note that all of these have their pros and cons. If you for instance for some reason are able to prove that all input from stdin
will have the right form and that you never fail to read from it, then by all means, deactivate the warning. Another thing could be that you have special needs, like extreme performance and/or very limited resources, or maybe some other reasons, it could be a wise choice to do a risk analysis for it and see if the risk is acceptable.
But as a general rule, do not inactivate compiler warnings unless you are very, very certain that the thing the compiler is warning about will not cause trouble. "I don't want to see a a lot of warnings" is not a good reason for disabling warnings.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments