Inline functions in C++
The main use of the inline function in C++ is to save time. Whenever the function is
called, then it takes a lot of time to execute the tasks, such as moving to the calling
function.
If the length of the function is small, then the substantial amount of execution time is
spent in switching.
Sometimes time required for jumping to the function definition takes greater time than
time required to execute that function.
C++ has provided one solution to this problem is called inline function.
When the function is encountered inside the main() method, it is expanded with its
definition thus saving time.
We cannot provide the inlining to the functions in the following circumstances:
o If a function is recursive.
o If a function contains a loop like for, while, do-while loop.
o If a function contains static variables.
o If a function contains a switch or go to statement
Syntax:
inline return-type function-name(parameters)
{
// function code
}
Page 1 of 2
Note inline is only a request to the compiler, not a command. The
compiler can ignore the request for inlining.
#include <iostream>
using namespace std;
inline int cube(int s) { return s * s * s; }
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
Page 2 of 2