There are no items in your cart
Add More
Add More
Item Details | Price |
---|
Inline function in C++
Ever wonder why do we use functions? Simple, because it helps in saving the memory space. It becomes even more helpful in the case when it is called even more times. But whenever the function is called, a lot of time is taken in completing various tasks like moving to the calling function. If the function is small, a very fair amount of time gets used in likewise overheads, and the time taken to move to the calling function is higher than the time consumes in completing that function.
So how do you solve this problem? By using a macro definition like macros. In C, Preprocessor macros are quite popular. However, the main drawback of it is that they are not functions. Hence, you cannot find the usual error checking process does during compilation.
There is a tad-bit different solution in C++ for this problem. If you wish to remove the call time to small functions, a new function is proposed by C++ - inline function. This is the function that is expanded in line at the time it is being invoked, thereby helping in saving time. The function call is replaced by the compiler with the respective function code, which decreased the overhead of function calls.
It should be noted that inlining is simply a request made to the compiler. It is not a command. The request fro inlining can be ignored by the compiler, and it may not execute inlining in these circumstances:
If a function is recursive.
If a function contains a loop. (for, while, do-while)
If a function contains a switch command or goto statement.
If a function contains static variables.
For a function not returning values, if a return statement exists.
Syntax:
For an inline function, declaration and definition must be done together.
inline function-header
{
function-body
}
Example:
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
inline int inc(int a)
{
return ++a;
}
int main()
{
int a = 11;
cout << "The cube of 3 is: " << cube(3) << "n";
cout << "Incrementing a " << inc(a) << "n";
return 0;
}
Output:
The Cube of 3 is: 27
Incrementing a 12
[Finished in 2.1s]
When to use Inline function?
The Inline function can utilize as the need. To check some of the important recommendations, read ahead -
Points to be remembered when utilizing Inline functions
What are the advantages of Inline function?