Inline Function and Its Usage in C++

Inline function Definition

In C++, The inline function is a powerful option to increase the performance of the program. 
An inline function needs to append inline keyword before function and looks like the normal function.But at the compile time Compiler replaces the function definition of the inline function instead of calling function definition at the runtime. 

How Inline function Works?

Important thing is, It is a suggestion to the compiler.The compiler may reject the suggestion for inlining function and It treats as normal function. 

The compiler checks the following criteria for the inline function:

  • The function should not contain static variables.
  • The function should not contain switch, loops and goto statement.
  • The function should not be a recursive function.
  • The function should not be big.
  • The function should have return statement or return type should be void.

Advantages

  • It speeds up the function calls by avoiding overhead calls of functions.
  • It increases the performance of the program.
  • The push or pop in a stack does not happen in a function as there are no overhead calls.

Disadvantages

  • An inline function uses cache memory and hence the increase in cache results in the poor execution of the program.
  • Having more number if inline functions can also reduce the speed as it adds more weight to the cache.
  • The size of the executable file increases as the code is expanded.
  • Since these functions are resolved at compile time, when the program code is changed, it is compulsory to compile the program again before running it.

Syntax

inline return_type function_name( param_1,param_2 ... param_n )
{
  //inline function body
}

Example Program

//Simple Inline Function Example Program in C++
//Function Example

#include<iostream>
#include<conio.h>

using namespace std;

inline int square(int x);

int main() {
   int a = 100, b = 200;
   cout << "Simple Inline Function Example Program in C++\n";

   cout << "\nSquare value for " << a << " is          :" << square(a);
   cout << "\nSquare value for " << b << " is          :" << square(b);

   getch();
}

// Inline square function
inline int square(int x) {
   return (x * x);
}

Sample Output

Simple Inline Function Example Program in C++

Square value for 100 is          :10000
Square value for 200 is          :40000