Inline Functions in C++

In this article, we will learn about inline functions, its working and how it is different than normal function in C++.

inline function in c++
liveoncode

Inline function is function from which compiler copies code into calling function directly rather than branching to the called function.

Since there is no branching and code is directly inserted it eliminates the performance overhead of function call.  overhead meaning  putting the parameters on the stack, entering and leaving the function, and a stack fix-up after the function returns.


How does Inline function works

inline function and its working in c++
Inline function working in C++

Here, while function call is made from program to inline function. Inline function code is copied to program.


Example of Inline function

//program to calculate sqaure of a number

 #include <iostream>
 #using namespace std; 
 inline void square(int value)   //inline function
  {
    value* = value;  //is equal to value = value * value
  }
 int main()
 {
   int x;
   cout << "enter a number to get its sqaure: ";
   cin >> x;
   square( x );
   cout << x;
   return 0;
 }   

Here, The inline modifier provides C++ a valuable hint it can use when generating code.Inline tells the compiler that the code is extremely small and simple. 

In above example will be represented as follow:

 #include <iostream>
 #using namespace std; 
 inline void square(int value)   //inline function
  {
    value* = value;  //is equal to value = value * value
  }
 int main()
 {
   int x;
   cout << "enter a number to get its sqaure: ";
   cin >> x;
   x *= x;   // here the inline method sqare will be copied
   cout << x;
   return 0;
 }   

Output

enter a number to get its sqaure: 7
49

If Compiler cannot generate Inline method it will be taken as an ordinary function.