Inline Function in C++

programming

Summary: In this tutorial, we will learn the significance of the inline function in C++.

To understand the concept of the inline function in C++, we first need to understand how the function call works and the overhead associated with it.

What is Function Call Overhead?

C++ maintains a separate stack for functions known as function stack to hold the activation records of the active functions.

An activation record is a collection of information that represents an active function. This is where the parameters, local variables, return address, and other metadata of a function is stored. It is also known as Stack Frame.

How function call works in C++

Whenever a function is called, its activation record is pushed into the stack and pop out when the function terminates.

inline function in C++

If the function is huge, the pushing, managing, and popping of its activation record consume time.

Although all this happens quickly and efficiently, it still happens. And when it’s repeated multiple times (i.e. function gets called multiple times), it becomes an overhead.

To get rid of this overhead, we use inline function in C++.

What is Inline Function?

For some functions, the time of managing them in the function stack may exceed the time required to execute them. Certainly, we would not like that to happen.

In such cases, we can ask the compiler to generate inline codes for such functions by preceding their function declaration with the inline keyword.

Inline codes are basically the assembly codes that avoid stack management and, therefore are faster.

Syntax for Inline Function:

inline <return_type> <funtion_name>()
{
    //Statements
}

We should always try to declare inline functions in the header or .h files, so that we can use its definition in multiple source files.

C++ Example: Inline Function

#include <iostream>
using namespace std;
 
//Inline Function
inline int add(int a, int b){
    return a+b;
}
 
int main()
{
    int a, b;
 
    cout << "Enter 2 Numbers \n";
    cin >> a;
    cin >> b;
 
    cout << "Sum: "<< add(a,b);
 
    return 0;
}

Output:

Inline function in C++ with example

Overview

  • Compilers sometimes intelligently create the inline code for the smaller functions, even without our suggestion.
  • Using inline in the function deceleration is a request to make a function inline, not a command. It depends on the compiler, whether to follow it or not.
  • Too many inline functions could lead to duplicates and the generation of larger binaries.
  • The execution of the inline function is usually faster than the normal C++ function.

Leave a Reply

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