Home > Mobile >  Warnings vs optimization gcc
Warnings vs optimization gcc

Time:12-31

I wonder if the warnings reported by compiler such as variable unused or control reaches end of a non-void function can impact a program (i.e crash) when the optimization is enabled (O2 or O3)

Could you please give me some examples ?

CodePudding user response:

Warnings indicate likely mistakes in your code. However, whether or not the warning is there or whether or not optimizations are enabled doesn't affect whether the code is correct.

Warnings such as unused variable simply indicate that you probably meant to use the variable somewhere but forgot to do so. Otherwise there wouldn't be a reason for the variable to be there.

Warnings such as control reaches end of a non-void function are more severe. For example in this specific case, calling a function with non-void return type causes undefined behavior if its execution reaches the function body's closing } without returning via a return statement prior to that.

In this case the warning is informing you that the compiler detected a path that the function could take for some input with this result. This is very likely unintended, because if you call that function taking that path, then your program would have undefined behavior.


When the program has undefined behavior you cannot be sure what it will do, absent additional guarantees made by your compiler/platform. It may behave in one way with optimizations and in a different way without them. It might also have different behavior with different compiler versions or just between different compilation runs or even program executions.

Higher optimization levels are however more likely to yield unexpected behavior in such a situation, because the compiler tries harder to transform the code into a more performant form and in doing so it will make assumptions on code constructs to not yield undefined behavior to expand the range of possible transformations.

  • Related