what is inline function in c++
Quick Scoop An inline function in C++ is a function marked with the
inline keyword, or one defined inside a class definition, that suggests the
compiler may replace the function call with the function’s actual code at the
call site. This can reduce function-call overhead for small, frequently used
functions, but the compiler is free to ignore the request.
How it works
Instead of jumping to a separate function body, the compiler may “paste” the function logic directly where it’s called. That is why inline functions are often used for short getters, setters, and simple utility functions.
Important points
inlineis a hint , not a guarantee.
- Inline functions can be defined in headers and included in multiple source files without causing multiple-definition errors, as long as the definitions are identical.
- Functions defined inside a class are implicitly inline.
- The compiler may choose not to inline large, recursive, or more complex functions.
Example
cpp
#include <iostream>
using namespace std;
inline int add(int a, int b) {
return a + b;
}
int main() {
cout << add(2, 3) << endl;
}
Here, add() is short, so it’s a common candidate for inlining.
Why use it
Use inline functions when you want simple, reusable code with less call overhead and safe header-based definitions. For big functions, inline usually gives little benefit and can even increase code size.
TL;DR: An inline function is a small C++ function the compiler may expand at the call site to avoid function-call overhead, but it is not forced to do so.