Inline Function in C++

When a normal function is called, the execution control goes into the called function and returns back to the caller upon completion of the called function. But in C++, if a function is marked as ‘inline‘, the compiler substitutes the code within the function definition for every instance of a function call. In case of an inline function call, the standard function call mechanism is not involved. The substituted code will get directly executed.

This improves the performance of the program as the function call overhead is bypassed. But it increases the compiled (linked) executable size, as the code of the inline function is replicated everywhere the call is made.

Overall this mechanism will be beneficial if we make the very small functions inline – not the big ones.

The standalone or a class member function can be made inline.

 #include <iostream>
using namespace std;

inline int max( int a , int b ) {
   if( a > b ) return a;
   return b;
}


int main() {
    
    cout << "Max between 5 and 6 is: " << max(5, 6) << endl;

    return 0;
}
$ g++ -o test test.cpp 
$ ./test 
Max between 5 and 6 is: 6

Code wise, there is no difference between a normal and an inline function expect the ‘inline‘ keyword preceding the function definition.

Inline Function Criteria

Not all functions could be made inline. The inline functions will have these criteria.

  1. Must return something. Inline functions should not return void.
  2. No loops. Inline functions should not have any loop.
  3. No static variable inside the function.
  4. Must be a non-recursive one.
  5. No switch or goto statement inside the function.

If a function does not meet any of these criteria, the compiler will treat the function as a normal function even if the function is preceded by the ‘inline‘ keyword.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

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

0
0
0
0
0
0