Inline functions
suggest changeIntroduction
A function defined with the inline specifier is an inline function. An inline function can be multiply defined without violating the One Definition Rule, and can therefore be defined in a header with external linkage. Declaring a function inline hints to the compiler that the function should be inlined during code generation, but does not provide a guarantee.
Syntax
inlinefunction_declarationinlinefunction_definition- class { function_definition };
Remarks
Usually if code generated for a function is sufficiently small then it’s a good candidate to be inlined. Why so? If a function is large and is inlined in a loop, for all the calls made, the large function’s code would be duplicated leading to the generated binary size bloat. But, how small is sufficient?
While inline functions seem to be a great way to avoid function-call overhead, not every function marked inline is inlined. inline is a hint, not an order: the compiler is not obliged to inline the function. Modern compilers inline when they see a benefit, including functions that are not marked inline. The keyword still matters for linkage, as the next section describes.
Inline as a linkage directive
The more practical use of inline in modern C++ is the One Definition Rule. When defining, not merely declaring, a function in a header that is included in multiple sources, each translation unit has a copy of that function. That would be an ODR (One Definition Rule) violation for an ordinary function with external linkage: there can be only one definition of such a function. Marking the definition inline allows those identical definitions. The function still has external linkage unless it is also declared static. The linker keeps one definition.
FAQs
When should I write the keyword ‘inline’ for a function/method in C++?
Only when you want the function to be defined in a header. More exactly only when the function’s definition can show up in multiple compilation units. 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.
When should I not write the keyword ‘inline’ for a function/method in C++?
Don’t add inline when you think your code will run faster if the compiler inlines it.
When might the compiler decline to inline a function?
Generally, the compiler will be able to do this better than you. However, the compiler doesn’t have the option to inline code if it doesn’t have the function definition. In maximally optimized code usually all private methods are inlined whether you ask for it or not.