What is an Inline Function in C++?
A inline function is a special function where the compiler replaces the function call with the actual code of the function. This helps your small functions run faster because there’s no jumping back and forth.
It’s great for tiny tasks that are used often — like printing messages or adding two numbers. 🧠⚡
✅ Why Use Inline Functions?
- Speeds up small, frequently used functions
- Reduces the cost of calling a function
- Keeps your code clean without sacrificing performance
🧠 Syntax of Inline Function
inline return_type function_name(parameters) { // function body }
🔧 Example: Say Hello with Inline Function
This simple function prints a greeting using the inline
keyword:
#include <iostream> using namespace std; inline void sayHello() { cout << "Hello, coder!" << endl; } int main() { sayHello(); // Code gets copied here sayHello(); // And again here! return 0; }
📌 When to Use Inline Functions
- Use for short functions (less than 5 lines)
- Avoid using with loops, recursion, or complex logic
- Compiler may ignore
inline
if it decides it’s not efficient
💡 Example: Inline Add Function
Here’s a simple inline function that adds two numbers:
#include <iostream> using namespace std; inline int add(int a, int b) { return a + b; } int main() { cout << "Total: " << add(7, 3) << endl; return 0; }
🎯 Summary
- Inline functions copy the function code directly into the caller
- Useful for fast execution of small, simple functions
- Can improve performance in certain cases
Use them like a shortcut for tiny jobs — faster, simpler, and cleaner! 🚀