Topic 34 of 83
Inline Functions
Overview
The `inline` keyword requests the compiler to insert the function's code directly into the caller's code, removing the overhead of a function call. It is used for very short, frequently called functions.
Syntax
cpp
inline int square(int x) {
return x * x;
}Common Pitfalls
- Inlining large functions drastically increases the size of the compiled binary (code bloat).
Interview Tips
- Explain that `inline` is just a 'request' to the compiler. Modern compilers are smart enough to inline functions automatically, and they will ignore the inline request if the function is too large or recursive.
Real-World Example
Optimizing a mathematical calculation in a tight loop.
example
cpp
#include <iostream>
using namespace std;
inline int max_val(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int max = 0;
// Without inline, this loop would make 10,000 function calls
for(int i = 0; i < 10000; i++) {
max = max_val(max, i);
}
return 0;
}