2

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?

Karl Alexius
  • 313
  • 1
  • 6
  • 15
  • See also [constexpr if](http://en.cppreference.com/w/cpp/language/if#Constexpr_If). – MSalters Jun 29 '17 at 14:25
  • This completely depends on the compiler but from what I have seen my guess is the compiler won't generate any code from that (though it will, of course, still syntax check it all). – Galik Jun 29 '17 at 14:33

2 Answers2

3

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.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
2

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

Curious
  • 20,870
  • 8
  • 61
  • 146
  • 1
    Naming this technique would improve the answer: I believe it is called "dead code elimination". The code is "dead" because it cannot be reached. (note that an `if (false) { body }` can be reached if there are labels within `body` that are `goto`'d) – Yakk - Adam Nevraumont Jun 29 '17 at 14:51
  • @Yakk always learn things from your answers and comments! Thanks – Curious Jun 29 '17 at 14:58
  • The goto thing is a really great spot. Assuming there are no goto statements and that compiler flags (e.g. -O2) are used to optimize and eliminate those lines, is it still worth to refactor your code? – Karl Alexius Jun 29 '17 at 15:45