This question already has an answer here:
How does compiler calculate which function should be inline since inline request is not obligatory? What kind of functions should I make inline?
Extra question. Can I make an inline call?
void func{} // normal (not-inline) function
int main()
{
func(); // normal call
// inline func(); // inline call
return 0;
}
When you are mark a function as
inline
you are advising the compiler that this function should be inlined. On (good) compilers this neither guarantees it will be, nor does it's absence guarantee it won't be.All inlining a function does is replace the call to the function with the body of the code. So while you can't suggest where the compiler should inline the function, you obviously could actually paste the code in (or use a macro to ensure the code stays the same). But you'd need a really good/odd reason to do this.
In general, mark small functions as inline if you wish, but otherwise leave it to the compiler.
What
inline
does is recommend to the compiler to replace any calls to this function with the actual code of the function, as T. Kiley said a while ago. The compiler does not have to do this, but if it does, this is what happens:If you have this function:
the compiler will replace all statements like
with
If your function was longer than a few lines, the finished executable size would increase, since every call would be replaced with the entire code of the function. (what other drawbacks are there?)
inline
is for functions that are trivially short (1 line).(from wiki) In various versions of the C and C++ programming languages, an inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined. Compilers are not obligated to respect this request.
In C++, you can use
__forceinline
keyword allow the programmer to force the compiler to inline the function, but indiscriminate use of__forceinline
can result in larger code (bloated executable file), minimal or no performance gain, and in some cases even a loss in performance.Small functions. It's a good idea to define small (as in one liner) functions in the header file as it gives the compiler more information to work with while optimizing your code. It also increases compilation time.
Check out When should I write the keyword 'inline' for a function/method? for more info.
inline
can only used in function declaration, not calling. You just need to call a pre-defined inline function as normal functions.