Warnings when activating optimization options

I use scanf in program c to read int from STDIN:

scanf("%d", &n); 

when I compile a c program with optimization enabled, I get a few warnings:

 gcc main.c -lm -lpthread -O2 -o main main.c: In function 'main': main.c:45: warning: ignoring return value of 'scanf', declared with attribute warn_unused_result main.c:50: warning: ignoring return value of 'scanf', declared with attribute warn_unused_result 

but when I remove the optimization options, why don't I get these warnings?

 gcc main.c -lm -lpthread -o main 

PS: I do not use -Wall or something like that.

+6
source share
2 answers

Changing optimizer settings changes how much (and how) the compiler analyzes your code.

Some analysis of the program flow is not performed if the optimization is not turned on (or is not set high enough), so corresponding warnings are not issued.
You will see that often for warnings there is an “unused variable” - this requires analysis of the code beyond what is necessary for its simple compilation, therefore you will use them only with optimization.

(And you really have to compile with -Wall .)

+9
source

-Wunused-result enabled by default : since you will need to decorate the function with __attribute__ ((warn_unused_result)) to trigger a warning, false positive effects only occur when they are used too liberally.

Even without passing additional flags, gcc should give a warning. However, as Mat explained, the compiler does not perform the necessary control flow analysis without increasing optimization levels.

Correct your code or disable the warning by adding -Wno-unused-result . Most likely will add a void value.

To drown out a warning in your code, you need to assign a return value to a dummy variable, which you can then apply to void to avoid a new warning about an unused variable. It is also possible to substitute a literary instance of C99 for an explicitly declared variable (verified with gcc 4.5.3).

This is really not optimal - I really expected the void -cast originally created to work ...

+3
source

Source: https://habr.com/ru/post/918233/


All Articles