Inline Functions
Performance optimization with inline
Interview Relevant: Optimization technique
Inline Functions
Inline suggests the compiler replace function calls with the function body.
Key Points
- inline: Hint to compiler, not a guarantee
- Reduces function call overhead
- Can increase code size (code bloat)
- Best for small, frequently called functions
- Functions in headers should be inline
Code Examples
Using inline functions for performance.
cpp
1// Inline function
2inline int max(int a, int b) {
3 return (a > b) ? a : b;
4}
5
6// constexpr functions are implicitly inline
7constexpr int square(int x) {
8 return x * x;
9}
10
11// Functions defined in class are implicitly inline
12class Math {
13 int add(int a, int b) { // Implicitly inline
14 return a + b;
15 }
16};
17
18// Modern C++17: inline variables
19inline int globalCounter = 0; // Can be in header
20
21// When NOT to use inline:
22// - Large functions
23// - Recursive functions
24// - Functions with loops