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.
- Must return something. Inline functions should not return void.
- No loops. Inline functions should not have any loop.
- No static variable inside the function.
- Must be a non-recursive one.
- 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.