C++ Notes to Self: Inline Functions
Inline functions is a feature of C++ that occurs during compile time. It allows us to avoid the runtime overhead of a function call during program execution. When a function is marked inline
, the compiler replaces every call the function with the function body. Inlining is always put in C++ header files. Because inlining obviates function calls, we avoid the performance overhead of stack and register housekeeping that regular function calls require.
Note that function inlining is not solely a language feature when using Visual Studio. We still have to got into the project settings. In DEBUG BUILD, all optimizations are turned off, including inlining. To overcome this, we set Project->Inline Functions-> Optimization->Inline Function Expansion to “Any Suitable /Obj2”.
Also note that because inlining is a compiler operation, it may ignore it all together. For example:
- Functions that are large
- Functions with too many conditional statements
- Recursive functions
- Functions invoked through pointers
In fact, modern compilers are very efficient. They may automatically inline regular functions to improve run time performance. We should keep inlining to very small functions. Inlining has the added overhead of increasing the size of the binary library or executable.
How do C-style macros compare with C++ inline functions?
- The macro preprocessor works by means of text substitution. With inline functions, the function body is substituted into the function call by the compiler.
- Macros are open to semantic errors while inline functions are semantically safe.
- Macros do not have a memory address while inline functions, just as regular ones, involve a memory address that we can see in disassembled code. This also means an inline function can be referenced or invoked through a pointer.
- Macros are difficult to use with multiple lines of code. This isn’t a problem with inline functions.
- Macros can’t be part of a C++ class. Inline functions can be encapsulated as class member functions.