web analytics

What is inline function? Give some uses of it.

Inline Function: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 that function, saving registers, pushing arguments into the stack and returning to the calling function. Also when a function is small a large percentage of execution time may be spent in such tasks to be done.
            That’s why inline functions are used. While the function is small inline functions are useful. An inline function is a function that is expanded in line when it is called. That is the compiler replaces the function call with the lines of codes of the function. Thus the jobs which get done when a function is called like, pushing arguments into the stack, returning to the calling function are not has to be done. So the execution time reduces.

            Example:The following example can show how to use an inline function,

//inline funciton
#include<iostream.h>

inline int cube(int x){
return x*x*x;
}

void main(){
int a,b,c;

/*The following 3 lines are calling the inline function. But here unlike usual the compiler will not go back to the called function, rather it will replace those places where it was called by the instruction lines from the called function which will reduce execution time*/

a=cube(2);
b=cube(3);
c=cube(5);
cout<<a<<","<<b<<","<<c;
}


            Output: 8,27,125
Use of Inline Function:

  1. Inline function should be used where the same function is called many times.
  2. Along with the given point (i) inline functions should be used where the functions are very small like of one or two lines.
  3. Also only when the inline function is not very complicated they can be used.

Thank you. Take a moment to share 🙏