Learn C++
#include "functions/inline.hpp"

inline Functions in C++

//concept

inline suggests the compiler paste a small function's body directly at call sites instead of paying call overhead — historically a manual optimization hint, today mostly a linkage tool: inline functions may be defined identically in multiple translation units (headers!) without multiple-definition linker errors.

Modern compilers inline aggressively on their own using cost models far smarter than human hints, so write inline for header-defined helpers and tiny accessors, and let -O2 decide the rest. Member functions defined inside a class body are implicitly inline for the same reason.

//how it works
1

A hint, not a command

The compiler may inline any suitable function and ignore inline on huge ones — it optimizes by measured cost, not by keyword.

2

Headers need it

A non-inline function defined in a header included by two .cpp files triggers multiple-definition link errors; inline (and templates, and constexpr) are exempt.

3

Class bodies imply it

Member functions written inside the class definition are implicitly inline — another reason tiny getters live in the class body.

4

Measure, don't sprinkle

Inlining trades binary size for speed; profile-guided and link-time optimization (-flto) beat manual inline placement.

//example
#include <iostream>
 
inline int square(int x) { return x * x; }
 
int main() {
std::cout << square(6) << std::endl;
return 0;
}
Output
36
1square is tiny and marked inline — the compiler will likely emit 6 * 6 directly with no call instruction.
2Even without the keyword, -O2 would inline this anyway; the keyword's real job here is safe header placement.
336 prints either way — inline changes code generation, never observable behavior.
//use cases
Header-only helpers and tiny utilities shared across translation units
Getters/setters defined inside class bodies (implicitly inline, zero overhead)
Understanding why templates and constexpr never cause multiple-definition errors
Letting -O2/-flto make the real inlining decisions while you write clear code

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.