Lesson 6 of 8
inline Functions & Recursion
`inline` is a hint to the compiler to substitute the function body at the call site, eliminating function call overhead. Modern compilers aggressively inline small functions even without the keyword, and may ignore `inline` for large functions. The other critical use of `inline` is for **ODR compliance** - functions defined in headers must be marked `inline`. Recursion is powerful but has a cost: each call allocates a stack frame. Deep recursion (tens of thousands of frames) causes stack overflow.
inline Functions, Recursion & Memoization
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
// ── inline - primarily for header definitions ─────────────────
// Without inline: including this header in 2 .cpp files → ODR violation
inline double to_radians(double deg) {
return deg * 3.14159265358979 / 180.0;
}
// small functions in class bodies are implicitly inline
class Vec2 {
public:
double x, y;
// implicitly inline (defined inside class)
double length() const { return std::sqrt(x*x + y*y); }
};
// ── Recursion - factorial (classic) ─────────────────────────
long long factorial(int n) {
if (n <= 1) return 1; // base case - MUST exist
return n * factorial(n - 1); // recursive case
}
// Stack depth: O(n) - for n=10000 → stack overflow!
// ── Tail recursion - compiler can optimize to a loop ─────────
// (not guaranteed in C++, unlike Scheme/Haskell, but clang/gcc do it with -O2)
long long factorial_tail(int n, long long acc = 1) {
if (n <= 1) return acc;
return factorial_tail(n - 1, n * acc); // tail call: last operation
}
// ── Memoization - cache results to avoid repeat computation ───
std::unordered_map<int, long long> fib_cache;
long long fibonacci(int n) {
if (n <= 1) return n;
auto it = fib_cache.find(n);
if (it != fib_cache.end()) return it->second; // cache hit
long long result = fibonacci(n-1) + fibonacci(n-2);
fib_cache[n] = result; // cache miss: store result
return result;
}
// Without memoization: O(2^n) - fib(50) would take hours
// With memoization: O(n) - fib(50) is instant
// ── Tree traversal - natural recursion ───────────────────────
struct TreeNode {
int val;
TreeNode *left = nullptr, *right = nullptr;
};
int tree_sum(const TreeNode* node) {
if (!node) return 0; // base case: null node
return node->val + tree_sum(node->left) + tree_sum(node->right);
}
int main() {
std::cout << "10! = " << factorial(10) << "
"; // 3628800
std::cout << "10!t = " << factorial_tail(10) << "
"; // 3628800
std::cout << "fib(40) = " << fibonacci(40) << "
"; // 102334155 (instant)
std::cout << "fib(50) = " << fibonacci(50) << "
"; // instant with memo
// Binary tree: 1, left=2, right=3
TreeNode root{1};
TreeNode left{2}, right{3};
root.left = &left; root.right = &right;
std::cout << "tree sum = " << tree_sum(&root) << "
"; // 6
return 0;
}Common Mistakes
- Missing base case in recursion - a recursive function with no base case (or an unreachable one) recurses infinitely until stack overflow. Always verify: what value of the input terminates the recursion?
- `inline` is not a performance guarantee - the compiler may ignore the `inline` hint for large functions. Conversely, it will inline small functions that aren't marked `inline`. The compiler's inlining decisions (visible with `-O2 -Winline`) are usually better than manual ones.
- Exponential recursion without memoization - `fibonacci(n)` without caching calls `fibonacci(n-1)` AND `fibonacci(n-2)`, each of which does the same. This is O(2ⁿ). Any recursive solution with overlapping sub-problems needs memoization (or convert to iteration).
Tip
Tip
Practice inline Functions Recursion in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Eliminating Function Call Overhead via Inlining, and Recursion Base Case Guarantees
Practice Task
Note
Practice Task - (1) Write a working example of inline Functions Recursion from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with inline Functions Recursion is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- `inline` is a hint to the compiler to substitute the function body at the call site, eliminating function call overhead.
- Missing base case in recursion - a recursive function with no base case (or an unreachable one) recurses infinitely until stack overflow. Always verify: what value of the input terminates the recursion?
- `inline` is not a performance guarantee - the compiler may ignore the `inline` hint for large functions. Conversely, it will inline small functions that aren't marked `inline`. The compiler's inlining decisions (visible with `-O2 -Winline`) are usually better than manual ones.
- Exponential recursion without memoization - `fibonacci(n)` without caching calls `fibonacci(n-1)` AND `fibonacci(n-2)`, each of which does the same. This is O(2ⁿ). Any recursive solution with overlapping sub-problems needs memoization (or convert to iteration).
Finished this lesson?