Site icon TechVidvan

C++ Inline Function with Examples

inline Functions in C++

The objective behind using a function is to save memory space. When you call a function, it takes a lot of extra time in performing tasks such as jumping to the calling function. Sometimes, the time taken for jumping to the calling function will be greater than the time taken to execute that function.

You can overcome this problem with the help of macros. But the main drawback of macros is that they are not functions that’s why the error checking won’t happen while compilation.

But in C++, you can make use of inline functions to completely ignore this problem. Let us learn more about inline function in C++.

Inline Function in C++

From the name you can easily say that an inline function is a function that is expanded in line when it is invoked. Also helps in saving time.

Using inline functions, the compiler will replace the function call with the function code which will reduce the overhead of function calls.

But below are some points in which the compiler may not perform inlining:-

Syntax of C++ Inline Function:-

inline function-header
{
// body of the function
}

Example of C++ inline function

#include <iostream>
using namespace std;
inline int square(int a)
{
return a*a;
}
inline int cube(int s)
{
return s*s*s;
}
int main()
{
int a = 5;
cout << "The cube of 5 is: " << cube(5) << endl;
cout << "Square of 5 is:  " << square(a) << endl;
return 0;
}

Output:-
The cube of 5 is: 125
Square of 5 is: 25

When to use inline function in C++?

Below are some useful conditions to use the inline functions in C++:-

Points to be noted when using C++ inline functions

Advantages of inline functions in C++

Disadvantages of inline functions in C++

Summary

This was all about the inline function in C++. We discussed when to use the inline function. We also discussed the advantages and limitations of the inline function.

Exit mobile version