Inline Functions in C++


Inline Functions in C++

Generally when a function call is executed the compiler before executing the function definition stores the address of function call, arguments, address of function definition into ‘Stack’.

Then it(stack) executes the statements in the function definition by assigning the values of arguments from the stack to the formal arguments from the stack to the formal arguments and returns back to the function call.

The entire process takes more time to execute the functions. So, whenever we have many function calls and when the function definition is very small then it is better to use “inline functions” that avoids much time to transfer the control here and there.

Inline functions are majorly used in the following situations :

  • when function definition definition is small.
  • When function does not contain any looping statements, switch case statements, Static variables and Recursive functions.

As said above inline functions in C++ should not contain :

  • Looping statements.
  • Switch case Statements
  • Static variables
  • Recursive functions.

When inline functions are used a function call is replaced by function definition instead of transferring the control.

Note : Generally these functions should be defined before main program.

Syntax for inline functions in C++:

inline datatype function_name(datatype arg1,datatype arg2,datatype arg3,.........,datatype argn)
   statement 1;
   statement 2;
   statement 3;
  statement n;

<em><strong>Example :</strong></em>
inline int add(int p, int q)
   return p+q;
int main()
  int p=100,q=200,r;
  cout&lt;&lt;"The addition of two numbers is ::"&lt;&lt;r&lt;&lt;endl;

<em><strong>output :</strong></em> 
         The addition of two numbers is :: 300.

About Author

Comments are closed.