bsobaid
bsobaid

Reputation: 975

c++ function inling decided at compile time

It is often said a function can be inlined only if it is known at the compile time how it will be called, or something to that effect. (pls correct/clarify if I am wrong)

So say if I have a function like this

void Calling()
{
if (m_InputState == State::Fast) //m_inputstate is a class member and is set by user
{
CallFastFunction();
}    
else if (m_InputState == State::Slow)
{
CallSlowFunction();
}
}

as m_inputstate is set by end-user, can we say this variable is not known at the compile time hence calling() cant be inlined?

Upvotes: 0

Views: 94

Answers (3)

Mats Petersson
Mats Petersson

Reputation: 129524

The compiler can (and almost certainly WILL) inline your Calling function. Depending on the availability of the source of CallFastFunction and CallSlowFunction, these may also be inlined.

If the compiler can determine the value of m_InputState, it will remove the if - but only if it's definitive that the value is one value.

For example, thing.m_InputState = State::Slow; thing.Calling(); will only compile in the "slow" call, without any conditonal code, where std::cin >> thing.m_InputState; thing.Calling(); will of course not.

If, through profile-based optimisation, the compiler knows how often each of the cases are chosen, it may also select which path ends up "next" in the order of the code, such that the most likely comes first (and it may also provide prefix or other indication to the processor that "you're likely going this way".

But inlining itself happens based on:

  1. The code itself being available.
  2. The size and number of calls to the function.
  3. Arbitrary compiler decisions that we can't know (unless we're very familiar with the source-code of the compiler).

Modern compilers also support "link time optimisation", where the object files produced are only "half-done", such that the linker will actually produce the final code, and it can move code around and inline, just the same as the old-fashioned compiler, on the entire code that makes up the executable (all the code using link-time optimisation), allowing code that didn't have the same source file or not in a header file to still be inlined.

Upvotes: 1

zargothrax
zargothrax

Reputation: 27

The fact that m_InputState is not known does not stop Calling() from being inlined.

Typically, if you want a function to be inlinable, it has to be declared in the same .cpp file that it is called in (no function prototypes). This depends a bit on the compiler though.

Upvotes: 0

Baum mit Augen
Baum mit Augen

Reputation: 50111

Inlining has nothing to do with the function input being known at compile time.

Upvotes: 3

Related Questions