Reputation: 428
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}
Upvotes: 4
Views: 621
Reputation: 129524
Modern compilers are incredibly clever, and often do "whole program optimization". So as long as you do sensible things, it definitely will optimise away function calls that just return a constant value. The compiler will also inline code that is only called once [even if it is very large], so writing small functions instead of large ones is definitely worth doing. Of course, using the function multiple times, it may not inline it, but then you get better cache hitrate from having the same function called from two places and smallr code overall.
Upvotes: 1
Reputation: 16320
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.)
Upvotes: 5
Reputation: 500933
I've just tried g++ 4.7.2
with -O3
, and in both examples it optimizes out the call. Without -O
, it doesn't.
Upvotes: 4