C++ Programming Inline Function


In this article, you will learn in-depth about C++ programming inline function with its working mechanism and explicit example.

inline function in C++

You will gain insight about:

  • How inline function works from its execution time to its flow?

  • How inline function works better for small functions?

C++ inline function: How is it different from regular function and why is it required?


Normally, a function call transfers the control from the calling program to the called function.

After the execution of the program, the called function returns the control to the calling program with a return value.

This concept of function saves program space because instead of writing same code multiple times the function stored in a place can be simply used by calling it at a desired place in the program.

This might be handy to reduce the program size but it definitely increases the execution time of the program as the function is invoked every time the control is passed to the function and returns a value after execution.

In large functions, this is very helpful but in a small function in order to save execution time a user may wish to put the code of function definition directly in the line of called location.

For this C++ provides inline function to reduce function call overhead. That is every time a function is called the compiler generate a copy of the function’s code in place to avoid function call.

This type of function whose code is copied to the called location is called inline function.

C++ programming inline function: syntax

inline data_type function_name(arguments_list); 

 

Good Programming Practice
Inline function should be used only with small and frequently used function because it makes the program to take more memory.

C++ programming inline function: Working mechanism


C++ programming inline function block diagram

As shown in above C++ inline function block diagram, whenever an inline function is called, instead of jumping to the function definition defined elsewhere, the body of function is executed at the line where it is called. It makes the execution much faster and efficient.

Note: Inline function can be used for small operations that require small codes to operate on.

C++ Inline Function Example

// inlinefunction.cpp
 #include <iostream>
 #using namespace std; 
 inline void square_me(int a)   //inline function
  {
    a* = a;
  }
 int main()
 {
   int x;
   cout << "enter number: ";
   cin >> x;
   square_me( x );
   cout << x;
   return 0;
 }           //end of the program

Output

enter number: 5
25

Explanation

In the above program, inline functioin square_me calculate the area of a square.

We can see that the definition of square_me function is written before it is used in the program.

This is important because the compiler knows how to place square_me function into its inlined code.