Functions
Inline Functions
Performance optimization with inline
Interview: Optimization technique
Inline Functions
The inline keyword suggests to the compiler to expand the function body at each call site instead of generating a function call instruction. This eliminates function call overhead (no stack frame push/pop, no branch), but increases binary size if the function is large.
Modern Usage: ODR, Not Performance
Modern compilers largely ignore the inline hint for performance — they inline aggressively based on their own heuristics. Today, inline primarily serves the ODR: an inline function can be defined in a header file and included in multiple translation units without causing linker errors (all definitions must be identical).
constexpr Implies Inline
constexpr functions are implicitly inline, making them safe to define in headers. They can be evaluated at compile time when called with constant expressions.
Interview Corner
Q: Does marking a function inline guarantee it will be inlined?
A: No. The inline keyword is a hint, not a directive. The compiler may refuse to inline if the function is too large, contains loops, or has its address taken. Conversely, compilers regularly inline functions not marked inline. For forced inlining, use __attribute__((always_inline)) (GCC/Clang) or __forceinline (MSVC) — though these are non-standard extensions.
Common Pitfalls
- Inlining large functions: Aggressively inlining large functions causes code bloat, which can thrash the instruction cache and reduce overall performance.
- inline in .cpp files: Marking a function inline in a .cpp file provides no ODR benefit — it's already in one translation unit. The benefit is only for headers.
Best Practices
- Define small, frequently called utility functions in header files with implicit or explicit inline for ODR compliance.
- Trust the compiler for inlining decisions in most cases; profile before manual tuning.