Karl Alexius
Karl Alexius

Reputation: 353

Does gcc/g++ generate the body of an if(false) statement?

In C++, imagine I have a function like

bool Aclass::func(){
   return true;
}

which is called in the main in this way

 if(!func()) { 
    //do stuff 
 }

Does the compiler generate these lines of code?

Upvotes: 2

Views: 535

Answers (2)

Curious
Curious

Reputation: 21510

The compiler at compilation step will treat those lines of code as valid. For example, if you have an error in those lines of code then it will be flagged by the compiler. So for example, the following will not compile

if (false) {
    auto s = std::string{1.0};
}

But most optimizers will not add that code in the compiled form for that source file. However related code is still added if needed, for example

if (true) { ... } 
else { ... }

here the else code for the else statement will essentially be converted to

{
   ...
} 

when the code gets converted to its compiled form.


@Yakk brings up a great point. The compiler not including such code is called dead code elimination. However labels can still be used to reach the body code.


Also note that in these situations where an expression is evaluated at compile time. Then you can use a new construct from C++17 known as if constexpr. However as I mentioned with compiler errors persisting even in dead code in runtime ifs the situation is different for if constexprs, for more read the code examples here http://en.cppreference.com/w/cpp/language/if#Constexpr_If and this answer https://stackoverflow.com/a/38317834/5501675

Upvotes: 2

François Andrieux
François Andrieux

Reputation: 29022

Like all optimization questions, it depends on the compiler and the flags given. Having said that, a decent modern compiler will be able to remove dead code like this if optimizations flags are provided. Try https://godbolt.org/ to see for yourself which compiler and which flags will succeed in removing the dead code.

Upvotes: 3

Related Questions