Can modern compilers optimize constant expressions where the expression is derived from a function?

I understand that modern C ++ compilers use shortcuts on things like:

if(true) {do stuff} 

But what about something like:

 bool foo(){return true} ... if(foo()) {do stuff} Or: class Functor { public: bool operator() () { return true;} } ... Functor f; if(f()){do stuff} 
+4
source share
3 answers

It depends on whether the compiler can see foo() in the same compiler.

If optimization is enabled, if foo() is in the same compilation unit as the callers, it will probably include a call to foo() , and then optimization will be simplified to the same if (true) check as before.

If you move foo() to a separate compilation unit, embedding can no longer be done, so most compilers will no longer be able to optimize this code. (Connection time optimization can be optimized in all compilation units, but this is much less common - not all compilers support it and are generally less efficient.)

+5
source

I just tried g++ 4.7.2 with -O3 and in both examples it optimizes the call. This is not true without -O .

+4
source

Modern compilers are incredibly smart and often perform "optimization of the entire program." That way, while you are doing reasonable things, it will definitely optimize function calls that return a constant value. The compiler will also embed code that is called only once (even if it is very large), so writing small functions instead of large ones is definitely worth it. Of course, using the function several times, it may not embed it, but then you will get the best cache hit from one function, called from two places and a small code as a whole.

+1
source

All Articles