C++ Inline Functions

In C++, the inline functions introduce an optimization technique to reduce the execution time of a program. It is quite similar to the concept of C macro function for reducing the execution time. However, these macro functions are only expanded (by the pre-processor) but not checked by the C compiler. But, C++ inline functions are real functions; so, they must be checked by the compiler.

When a normal function is called during runtime, the program stores the memory address of the instructions immediately following the function call statement, loads the called function 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. So, there is too much runtime overhead for calling a function.

The C++ inline function provides an alternative. Using inline keyword, the compiler replaces the function call statement with the function code itself (called expansion) and then compiles the entire code. Thus, with inline functions, the compiler does not have to jump to another location to execute the function, and then jump back as the code of the called function is already available to the calling program. Normally, small C++ functions are declared inline so as to make the program execution faster.

To create an inline function, we use the inline keyword:

inline return_type function_name (parameter list)  {    
    // function body
}

We must use the keyword inline before the function definition. Remember that it is just a suggestion to the C++ compiler to make the function inline, if the function is big (in terms of executable statements) then, compiler can ignore the “inline” request and consider the function as normal function.

 

 

Features of Inline Function

There are some key points of an inline function, among them:

  • An inline function speeds up the exceution by avoiding function call overhead. 
  • It saves overhead of variables push / pop on stack, when function is called.
  • An inline function saves overhead of return call from a function.
  • It increases locality of reference by utilizing instruction cache.
  • All the member functions defined within a class are inline by default. 

 

NOTE: C++ compiler can ignore the request for inlining if the function is recursive; contains loops, static variables, switch or goto statements, and is having void return type or doesn’t have a return type.

 

 

Example of Inline Function

Let us see a program involving an inline function.

#include <iostream>
using namespace std;

inline double multi(double a, double b) {
return a * b;
}

int main() {
cout << "Result1: " << multi(3, 5) << endl;
cout << "Result2: " << multi(5.7, 8) << endl;
cout << "Result3: " << multi(8.25, 15) << endl;
return 0;
}

Output:

Result1: 15
Result2: 45.6
Result3: 123.75