What Are Inline Functions?
The
inline keyword suggests to the compiler that it should replace function calls with the function's body directly at the call site. This eliminates the overhead of a function call (pushing arguments, jumping, returning) for small, frequently called functions.c
When to Use inline
Inline functions are most beneficial for:
- Small functions (1–5 lines)
- Frequently called functions (inside loops)
- Performance-critical sections
c
Important:inlineis a hint, not a command. The compiler is free to ignore it. Modern compilers with-O2or higher often inline functions automatically, even without the keyword.
inline vs Macros
Before C99 introduced
inline, developers used macros for "inline" behavior:c
| Feature | inline function | #define macro |
|---|---|---|
| Type checking | ✅ Yes | ❌ No |
| Debugging | ✅ Has symbol | ❌ No symbol |
| Side effects | ✅ Safe | ❌ Double evaluation |
| Scope | ✅ Respects scope | ❌ Textual substitution |
Best Practice: Preferinlinefunctions over macros for anything that behaves like a function. Use macros only for constants and conditional compilation.
static inline — The Common Pattern
In practice,
inline functions in header files should be static inline to avoid linker errors:c
Without
static, including the header in multiple .c files causes "multiple definition" linker errors.Summary
inlinesuggests the compiler replace calls with function body- Best for small, hot functions
- The compiler may ignore the hint — and that's fine
- Use
static inlinein headers to avoid linker issues - Prefer
inlinefunctions over function-like macros