Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

It is my understanding that modern c++ compilers take shortcuts on things like:

if(true)
{do stuff}

But how 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}
like image 693
QuarterlyQuotaOfQuotes Avatar asked Dec 27 '22 12:12

QuarterlyQuotaOfQuotes


1 Answers

It depends if the compiler can see foo() in the same compilation unit.

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

If you move foo() to a separate compilation unit, the inlining can no longer happen, so most compilers will no longer be able to optimize this code. (Link-time optimization can optimize across compilation units, but it's a lot less common--not all compilers support it and in general it's less effective.)

like image 146
StilesCrisis Avatar answered Jan 04 '23 23:01

StilesCrisis