Inline Functions in C++
Inline functions replace function calls with actual code at compile time, eliminating overhead.
Use 'inline' keyword for small, frequently called functions like getters/setters.
Compiler decides if inlining happens; it's a hint, not a command.
1. Why Use Inline Functions?
Normal calls: push parameters, jump, stack setup (overhead).
Inline: Code copied directly—no jump.
Benefits: Faster execution for tiny functions.
Drawbacks: Larger executable size.
2. Syntax and Declaration
inline int max(int a, int b) {
return (a > b) ? a : b;
}
Declare in header (.h); definition must be visible.
3. Simple Example
#include <iostream>
using namespace std;
inline int getSum(int a, int b) {
return a + b;
}
int main() {
cout << getSum(5, 3) << endl; // Expands to 5+3
return 0;
}
Output: 8. Compiler replaces call with code.
4. Inline in Classes
Member functions defined inside class are auto-inline.
class Rectangle {
public:
int width, height;
int area() { return width * height; } // Inline
};
5. When Compiler Ignores Inline
- Loops, recursion, switch.
- Static variables.
- Functions > ~10 lines.
6. Macros vs Inline Functions
Macros: Text replacement (unsafe).
#define SQUARE(x) ((x)*(x)) // Macro
inline int square(int x) { return x * x; } // Safe
Inline: Type-safe, no side-effect issues.
7. Best Practices
- Small/simple functions only.
- In headers for templates/classes.
- Profile before/after—don't assume speedup.
Conclusion
Inline functions optimize performance-critical code.
Use wisely; modern compilers inline smartly anyway.
Codecrown