Inline Function in C++

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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:

  1. For functions returning values if a loop, a switch or a go to exists.
  2. for function s not returning values, if a return statement exists.
  3. if functions contain static variables.
  4. 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

Related posts