Sunday, February 13, 2011

Inline functions


Inline functions
         When a same task is to done for many times, the function is used to save memory space. But, the use of function not only saves memory space but also adds extra overheads. One function call has to pass many steps like jumping to the function, saving registers, pushing arguments into the stack and returning to the calling function. A lot of time is taken by these instructions. When function is small, a substantial percentage of execution time may be spent in such overheads. In the case of small functions, the benefit obtained by saving memory is less important or meaningful in comparison to extra over heads during function call. In this situation, one may urge that the use of function is disadvantageous. They may say that instead of using function, using duplication of code to perform same task repeatedly is more advantageous. But duplication of code makes program unorganized and difficult to read.
         This problem is eliminated by inline function in C++. An inline function is a function that is expanded in line when it is invoked. The compiler replaces the function call with the corresponding function code. A function is made inline by adding prefix inline to the function definition. The syntax is
        Inline  return_type  function_name(argument_list)
             {
             }
An example:              
#include<iostream.h>
inline float interst(float p, float t, float r)
        { return ((p*t*r)/100); }

void main()
 {
   float result;
    result=interst(12000,2,10);
    cout<<"The interest is "<<result;
  }
In this example, the function interst is defined as inline.
                Defining inline function is meaningful only for small functions. For large functions, the function call becomes small compared to the execution of the function and the benefits of the inline functions may be lost. In such cases, the use of normal functions will be more meaningful. Usually, the functions are made inline when they are small enough to be defined in one or more lines. The inline keyword merely sends a request, not a command, to the compiler. Thus, compiler may ignore this request if the function definition is too long or too complicated and compile the function as a normal function.
            Although, inline expansion makes a program run faster because the overhead of a function call and return is eliminated, it makes the program to take up more memory because the statements that define the inline function are reproduced at each point where the function is called. So, a trade off becomes necessary.

When inline function may not work?
Ø  For large functions
Ø  For functions containing static variables
Ø  For recursive functions
Ø  For function containing a loop, a switch or a goto.

No comments:

Post a Comment