A function is a block of code that performs a specific task. It improves the readability of the code.

Syntax

Syntax of normal function and inline function is same except that inline function has the keyword inline in its definition. Below is the example showing both function types.

#include <iostream>
using namespace std;

// Inline function
inline int square_in(int s)
{
  return s*s;
}

// Normal function
int square(int s)
{
  return s*s;
}

void main()
{
  cout << square(5) << "\n";
}

Normal function vs Inline function

The coding of normal functions and inline functions is similar except that inline functions’ definitions start with the keyword inline. The distinction between normal functions and inline functions is the different compilation process for them.

After writing any program, it is first compiled to get an executable code. Which is then executed, the OS loads the instructions into the computer’s memory, so that each instruction is stored in a specific memory location. When a function call instruction is encountered, the compiler stores the memory address of the instruction immediately following the function call statement, loads the function being called into the memory, copies argument values, jumps to the memory location of the called function, executes the function code, stores the return value of the function, and then jumps back to the address of the instruction that was saved just before executing the called function.

The C++ inline function provides an alternative. With inline code, the compiler replaces the function call statement with the function code itself (this process is called expansion) and then compiles the entire code. Thus, with this the compiler doesn’t have to do the long, time consuming process. However, inline is just a request to the compiler that could be ignored.

Advantage is that, this save overheads of a function call as it’s not invoked, rather its code is replaced in the program. However with more function calls the repeated occurrences of same function code wastes memory space.