C++:inline
lastmod 2018-08-17created 2015-08-2210 edits
An inline function is a function, in several versions of the C and C++ programming languages, for which the compiler is requested to perform inline expansion. In other words, instead of generating code that calls the function where it is defined, the programmer can request that the compiler insert the complete function body at every place the function is called.
Restrictions
A summary of the restrictions on inline functions.
- Loop statements (do whie, while, for), switch, and goto cannot be used inside an inline function.
- When calling an inline function, the inline function must be defined before it is called.
- Recursive calls cannot be made inside an inline function.
- An inline function cannot be called more than once within a single expression.
- The address of an inline function cannot be taken with a function pointer.
This is because an inline function works by substitution and expansion, not by calling.
Tip
static/inline keyword position
- static/inline keyword: in front of prototype and/or implementation?
- Stackoverflow: Inline function prototype vs regular declaration vs prototype
Should keywords such as static or inline go on the Prorotype or the Implementation?
Answer: the Prototype.
Assembly result
Compares the Assembly output of the code below with and without the inline (__attribute__((always_inline))) syntax.
__attribute__((always_inline)) int add(int i)
{
return i + i;
}
int main()
{
int a = add(10);
return 0;
}
For reference, the output was extracted using objdump.
As the result shows, with inline the callq instruction is gone and the add instruction is included.
Favorite site
- Wikipedia (en) on Inline function
- [Recommended] Inline Functions
- GCC: An Inline Function is As Fast As a Macro
- inline keyword and inl file. ( *.inl )
- Splitting files in C++
- 4. Functions - function pointers, inline functions
- MSDN: Inline Functions (C++)
- GCC: An Inline Function is As Fast As a Macro
- Item 25: Dissecting inline ( difficulty: 7 )
- What is a C++ inline function? 1
References
-
Netrance.blog.naver.com_-inline_function-_asm.pdf ↩