What is inline function?
An inline function is a function that is expanded in line when it is invoked. Inline expansion makes a program run faster because the overhead of a function call and return is eliminated. It is defined by using key word “inline”.
To eliminate the cost of calls to small functions C++ proposes a new feature called inline function. An inline function is a function that is expanded inline when it is invoked .That is the compiler replaces the function call with the corresponding function code.
syntax:
inline function-header
{
function body;
}
Example:
inline double cube (double a)
{
return(a*a*a);
}
The above inline function can be invoked by statements like
c=cube(3.0);
d=cube(2.5+1.5);
Remember that the inline keyword merely sends a request, not a command to the compiler. The compiler may ignore this request if the function definition is too long or too complicated and compile the function as a normal function.
Characteristics of Inline Function:
- One of the objectives of using functions in a program is to save some memory space, which becomes appreciable when a function is likely to be called many times.
- Every time a function is called, it takes a lot of extra time in executing a series of instructions for tasks such as jumping to the function, saving registers, pushing arguments into the stack, and returning to the calling function.
- When a function is small, a substantial percentage of execution time may be spent in such overheads. One solution to this problem is to use macro definitions, known as macros.
- Pre-processor macros are popular in C. The major drawback with macros is that they are not really functions and therefore, the usual error checking does not occur during compilation.
- C++ has different solution to this problem. To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function.
Some of the situations where inline expansion may not work are:
- For functions returning values if a loop, a switch or a go to exists.
- for function s not returning values, if a return statement exists.
- if functions contain static variables.
- if inline functions are recursive,.
Example:
#include<iostream.h>
inline float mul(float x, float y)
{
return (x*y);
}
inline double div(double p, double q)
{
return (p/q);
}
int main()
{
float a=12.345;
float b=9.82;
cout<<mul(a,b);
cout<<div(a,b);
return 0;
}
Output:
121.227898
1.257128
You must log in to post a comment.