Now In this article I am going to explain about Inline Function in C++. also explain in such a way that you are able to understand and answer the following questions that arise in your mind 💧What is Inline function ? 💧Why it is useful in C++ programming? 💧When it is used? 💧 How it is used?
Inline Function:
It is an important feature of C++ programming. As the name says Inline function that means it is a function followed by keyword Inline. Some time we need to call any function many times in a program than Inline function is useful.But if our function have number of line of code or simply we can say that function is big in size than it will take lot of time for compiling each line of code and if we call again and again a lot of memory is wastage. Most of the time it busy for performing following tasks such as 💧 jumping to the function.💧 Saving registers💧 Pushing argument into the stack and return to calling function.
So we can say that it take lot of extra time for executing the instructions and perform above tasks.
So, to eliminate the cost of calls to small function, C++ propose a new feature called Inline Function.
Inline function that replace the call with their definitions at the time of compilation.It is just like a macro in C
Syntax:
Inline function_header
{
function body;
}
Example :
inline void show()
{
cout <<"Inline Function";
}
void main()
{
show();
show();
show();
show();
}
Explanation :
Here inline function replace f() by cout <<"Inline Function" at compilation time.Here time is saved but memory space is waste.
All inline function must be define before they are called. If the function is large in size then inline function work in slower speed. It is beneficial in small function which is written in one or two lines.
Example:
#include <iostream.h>
#include <conio.h>
inline float mul(float a, float b)
{
return (a * b);
}
inline double div(double x, double y)
{
return (x / y);
}
main()
{
float p=12.345;
float q=9.82;
cout << mul (p , q)<<"\n";
cout << div ( p , q)<<"\n";
}
Note: When we are using inline function then there are some restriction that have to be in mind such as Any inline function doesn't have any looping statements inside inline function.
Any inline function doesn't have any if-else statements inside inline function.
Any inline function doesn't have any break statements inside inline function.
Any inline function doesn't have any continue statements inside inline function.
Any inline function doesn't have any goto statements inside inline function.
Any inline function doesn't have any switch statements inside inline function.
So, we can say that it is a function contain simple statements.
No comments:
Post a Comment