To understand the concept of inline function in C++, we first need to understand how function call works?

The function uses an area in the memory called function stack or program stack (Last In First Out). Each time a function gets called its Activation record is created and is pushed on to the function stack.

How function call works in C++

Activation Record is a collection of information that represents an active function. This is where the parameters, local variables, return address and more are stored. It is also known as Stack Frame.

When the function terminates, its activation records is popped from the stack and now the top of the stack is the activation record of the function which called this function- which was just now popped off.

inline function in C++

If the function is huge, the pushing, managing, and popping of its activation record consume a little time. Although this all happens quickly and efficiently, it still happens. And when it is repeated number of times (i.e function gets called multiple times), it becomes an overhead.

To get rid of this overhead we use inline function.

What is Inline Function?

Sometimes function overhead might be greater than the time spent to execute that function. In such case we can tell compiler to generate inline code.

Inline code is basically inline assembly code that avoids overhead (i.e stack management) and therefore, is generally faster.

A function can be made inline function by preceding the function declaration with inline keyword.

C++ Inline Function Syntax

Inline functions are usually declared in the header or .h files, so that its definition is available to every source file that uses it.

C++ Inline Function Example

Following is a C++ example which uses an inline function.

Output

Inline function in C++ with example

C++ Inline Function Overview

  • Complers sometimes intelligently inline function, even without our suggestion.
  • Using inline in function deceleration is a request to make function inline not a command. It depends on compiler, whether to follow it or not.
  • Using inline function many times could lead to duplicates and generation of larger binaries
  • Execution of inline function are generally faster when compared to normal C++ function

That’s all introduction to C++ inline function. If you have any doubts, then do comment below.

Leave a Reply

Close Menu