Inline Function in C++

 


1️⃣ What is an Inline Function?

An inline function is a function that the compiler expands at the point of its call instead of executing a normal function call.

Avoids function call overhead (stack operations).
Increases execution speed by directly inserting the function code.
Best for small, frequently used functions.


2️⃣ Syntax

inline returnType functionName(parameters) {
    // Function body
}

3️⃣ Example: Inline Function in Action

#include <iostream>
using namespace std;

inline int square(int x) {  
    return x * x;
}

int main() {
    cout << "Square of 5: " << square(5) << endl;
    cout << "Square of 7: " << square(7) << endl;

    return 0;
}

🔹 Output

Square of 5: 25
Square of 7: 49

Why use inline?
✔ Avoids function call overhead.
square(5) is replaced directly with 5 * 5 in machine code.


4️⃣ How Inline Functions Work Internally?

Instead of generating a function call, the compiler expands the function at each call site.

🔹 Without Inline (Normal Function Call)

int square(int x) {
    return x * x;
}
int main() {
    int a = square(5);  // CALL square function
}

🔹 With Inline Function (Expanded Code)

int main() {
    int a = 5 * 5;  // No function call, directly replaced!
}

5️⃣ When to Use Inline Functions?

Use inline when:
✔ The function is small (one-liner or a few lines).
✔ The function is frequently used (e.g., math operations).
✔ The function does not contain loops, recursion, or complex logic.

🚫 Avoid inline when:
❌ The function is large (increases code size).
❌ The function contains loops, recursion, static variables.
❌ The function is virtual (because dynamic binding prevents inlining).


6️⃣ Example: When Inline is Not Applied

Inline functions won't be expanded if they contain complex operations like loops or recursion.

🔹 Example: Loop inside Inline Function

#include <iostream>
using namespace std;

inline void printNumbers(int n) {
    for (int i = 1; i <= n; i++) {  // Loop inside inline function
        cout << i << " ";
    }
    cout << endl;
}

int main() {
    printNumbers(5);  // Compiler may ignore inline here
    return 0;
}

Inline may be ignored! The loop makes the function complex, so the compiler may choose not to expand it.


7️⃣ Summary

Inline functions reduce function call overhead by expanding code at the call site.
Best for small, simple, and frequently used functions.
Avoid for complex functions with loops, recursion, or static variables.

Would you like an example with class and inline functions? 🚀

Post a Comment

0 Comments