Monday, October 15, 2012

Advantages and disadvantages of inline function in c++

The purpose of inline functions is to insert the code of a called function at the point where the function is called.It can improve the application's performance but not always.If you have two or three statements then it works otherwise compiler will ignore inline keyword.

    We put inline keyword in front of a function which requests a compiler to make that function as inline function. When we call an inline function, it expands (similar to macro) itself and skipped from actual function call as in case of normal functions happen. Let’s take a small example.


inline int minimum (int x, int y)
{
      return x < y ? x: y;
}

int main()
{
      cout << “minimum of 50 and 70 is” << minimum (50, 70);
      return 0;
}

As we put inline keyword so the function is expanded like below at the time of invocation.

int main()
{
      cout <<“minimum of 50 and 70 is” << (50 < 70? 50: 70;
      return 0;
}

Pros:

1. It increases performance.
2. It is better than macros because it does type checking.

Cons:

1. Compiler often generates a lot of low level code to implement inline functions.
2. It is necessary to write definition for an inline function (compared to normal function) in every module (compilation unit) that uses it otherwise it is not possible to compile a single module independently of all other modules.
3. If we use many inline functions then executable size will also be increased.
4. Little bit it breaks encapsulation because it exposes the internal of the objects






No comments:

Post a Comment