INLINE FUNCTION IN C++

                                                        Inline function

An inline function is a function for which the compiler replaces the function call with the actual function code at compile time.

 

Usability of Inline Functions

Problem with Normal Functions

Normal function calls cause:

  • Function call overhead
  • Stack memory usage
  • Slower execution for small functions

Inline Function

Inline functions:

  • Improve execution speed
  • Reduce function call overhead
  • Suitable for small and frequently used functions

Syntax of Inline Function

inline return_type function_name(parameters)

{

    // function body

}

 

Example : Inline Function to Add Two Numbers

#include <iostream>

using namespace std;

 

inline int add(int a, int b)

{

    return a + b;

}

 

int main()

{

    int x = 10, y = 20;

    cout << "Sum = " << add(x, y);

    return 0;

}

 

Process of Compiler Handles Inline Functions

Even if a function is declared inline:

  • The compiler may ignore it
  • Inline is only a request, not a command

 

Compiler may NOT inline if:

  • The function is large
  • Uses loops
  • Uses recursion
  • Uses static variables
  • Function complexity is high

Inline Function with Class

All functions defined inside a class are implicitly inline.

 

Example: Inline Function Inside Class

#include <iostream>

using namespace std;

 

class Demo

{

public:

    inline void show()

    {

        cout << "This is an inline member function";

    }

};

 

int main()

{

    Demo d;

    d.show();

    return 0;

}

 


Inline Function Defined Outside Class

 

Example

#include <iostream>

using namespace std;

 

class Sample

{

public:

    void display();

};

 

inline void Sample::display()

{

    cout << "Inline function outside class";

}

 

int main()

{

    Sample s;

    s.display();

    return 0;

}


Inline Function with Default Arguments

#include <iostream>

using namespace std;

 

inline int multiply(int a, int b = 2)

{

    return a * b;

}

 

int main()

{

    cout << multiply(5) << endl;

    cout << multiply(5, 3);

    return 0;

}


 

Advantages of Inline Functions

Faster execution
No function call overhead
Type safety
Better debugging
More readable than macros


 

Disadvantages of Inline Functions

Increases program size
Not suitable for large functions

The compiler may ignore it


When to Use Inline Functions?

Small functions
Frequently called functions
Simple logic (1–3 lines)

 

 Avoid for:

  • Recursive functions
  • Large code blocks
  • Complex logic

============================================================== 

Post a Comment

0 Comments