Problem in Using Normal Function

  • The main advantage of function is to save codding efforts, memory space and reusability.
  • But whenever we call a function, it consume  a lot of time say for example, when we are calling a function, computer save the program counter, variables into the stack and then start the execution of called function.
  • After the execution gets over of the called function, computer again fetches the program counter and variables from the stack and resumes its execution.
  • For large function this overhead is affordable but for small function this overhead puts extra time for execution.
Possible solution:
  • One solution for the above problem is to use macro definitions, known as macro. There is facility of preprocessor macro in C but it is not real function so it does not provide error checking during the compilation.

Inline function

  • C++ provides the solution for above problem by using inline function.
  • An inline function is a function, in which function definition is replaced at the place of function call in line during compilation.

  • We can make function inline by placing keyword ‘inline’ before the function definition.
  • Syntax for the inline function is as follow:
inline function-name(argument1, argument2, …)
     // function body...
  • As the function becomes large in size, the speed of inline function is decrease and some time it is better to call normal function rather than inline function.
  • Also function required more memory during compilation because after compilation your program becomes large because function call statement is replaced by the function definition code.
  • Inline function is request to compiler not command. So it is not compulsory that inline function is executed as inline.
  • It may be executed as normal function. Compiler execute the inline function as normal function in the following condition:
  1. When function is too large in size.
  2. When function is too complicated.
  3. When function contains static variables
  4. When function is recursive.
  5. If, switch, goto, or looping structure is used in the function.
  • Function call is made like a normal function as follow:.
 main( )
    cout << sum(50, 40);

 inline  int sum(int x, int y)
    return(a + b);

Note: In C++ when function definition is written inside the class, that function is considered as the inline by default.