Inline Function Explained With Simple Example

Inline function is an important addition in C++. These inline functions mostly are not called and is expanded in line at the invocation place. Hence, these functions are called inline functions. To define a function as inline function, precede function definition with “inline” keyword. These functions are almost similar to Macros in C.
For eg:

inline int sum (int a, int b);

Let’s have a look at example inline functions.

static inline int inline_function (int n)
{
    // Doing some random stuff
    int x = 20;
    int y = 55;
    int z = (x + y) * (y - x) * (x/y) * x * y;
    return z;
}

class InlineExample
{
    private:
        int m;
        // automatic inline
        InlineExample (int x): m(x)
        {}
        int get_value ()
        {
            return m;
        }
};

Advantages

  • Function call overhead is not needed.
  • Inline function typically has better performance as function call overhead is reduced.
  • Inline functions allow compiler to do optimization at specific invoking places which might not be possible with normal function call.
  • Inline functions are most useful in case function is small and called frequently.

Disadvantages

  • Since inline function expand the function code at invoking place, hence this could result in larger executable size.
  • Too much inline functions can negatively affect the performance of the program.
  • Inline very big functions can create very large sized executable.
  • It can increase compile time overhead.

Important points

  • Inline functions are just a recommendation to compiler just like “register”. Compiler may choose to ignore inline recommendations.
  • Compiler can ignore inline functions call in cases like
    • If function is recursive.
    • If function contains loops using for/while etc.
    • If function has static variables.

Leave a Reply

Your email address will not be published. Required fields are marked *