Explain 'INLINE' function with program in C++

Explain or define 'INLINE' function :-


Definitions:-

     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". 

Necessity of Inline Function:-

i) One of the objectives of using function in a program is to save some memory space, which becomes appreciable when a function is likely to be called many times. 
ii) Every time a function is called, it take a lot of extra time in executing a series of instruction for tasks such as jumping to the function, saving registers, pushing arguments into the stack, and returning to the calling function.
iii) 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, knowns as macros. Preprocessor 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.    iv) C++ has different solution to this problem. To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function.

General form:-

inline function-header   
{
   function body
}    

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;
}

Properties of inline function:-

1. Inline function sends request but not a command to compiler.
2. Compiler my serve or ignore the request .
3. If function has too many lines or if it has complicated logic then it executed as normal function.

Properties where inline does not work :-

1.A function is returning value, if it contains switch, loop or both then it is treated as normal function. 
2. If a function is not returning any value and it contains a return statement then it is treated as normal function.
3. If function contains static variables then it is executed as normal function.

Write a program to find a cube of a number using 'inline' function:-

#include<iostream.h>
#include<conio.h>
inline int cube(int s)
{
 return s*s*s;
}
int main()
{
clrscr();
cout<<"The cube of 3 is "<<cube(3)<<"/n";
getch();
return 0;
}
Output:
The cube of 3 is 
9


Hope this information is useful to you.


                                                                                                                                                                                                   

Md Ashraf

'KNOWLEDGE WITH ASHRAF' is the platform where you find all the type of knowledge especially on programming based. Our goal is to give you a deeper grasp of technology in specifics that will help you increase your knowledge.

Previous Post Next Post

Contact Form