Inline functions

Inline functions
Explains the need of inline functions, when to / not to use them and how to use them.

In this tutorial I’ll explain what inline functions are and after that I’ll show you an example of using inline functions.

If you don’t know yet, when in your code there’s a function, the program jumps to the address of the function and when it reaches the end of the function it comes back. This ‘jumping’ actually involves much more (copying the arguments of the function on the stack for example) and takes time.

The solution is inline functions. Where an inline function is called the compiler will replace the call with the function code. So in reality in that place there will be no function call, only the code of the function. No ‘jumping’ needed to different addresses, no fuss.

But now you may ask…

When should I use inline functions?

You have to be careful when to use inline functions and when not. Most of the time you won’t need to use inline functions as the performance gain is small.

The question actually is: When shouldn’t I use inline functions?

The answer to this question is also inexact. You should think about what using an inline function involves in some situations. For example you shouldn’t use inline functions when the function is called several times as this is a waste of space (think of 8 function calls, 8 copies of that function in the code).

Sometimes the compiler doesn’t care about your decision, if you want the function to be inline or not. If the compiler sees that you want to make a huge function inline it may not respect your decision. Also, there are cases in which some small functions are treated as inline by some compilers.

How do I use inline functions?

The following code creates and calls an inline function:

#include "stdafx.h"

// Uncomment the below line if you don't use managed C++

//#include <iostream>
using namespace std;

inline int average(int a, int b)


   return (a + b) / 2;


int main()


   int result = average(12, 14);

   cout << "The average of number 12, 14 is " << result << "\n";

   return 0;


Besides adding the keyword inline before the function, you also have to place the function above any other function that may call this one. This also excludes the posibility of making recursive functions (functions that call each other) inline.

Leave a Reply

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

Back To Top