Explain or define '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".
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:-
{
function body
}
Example:-
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:-
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 :-
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<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.