An inline function in C++ is a function that is expanded in line with the rest of the code, rather than being called as a separate function. The purpose of inline functions is to improve the performance of the program by reducing the overhead of function calls.
To create an inline function in C++, you can use the inline keyword before the function declaration, like this:
inline int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
When the compiler encounters an inline function, it expands the function body in place of the function call, rather than generating code to call the function. This can improve the performance of the program, especially for small functions that are called frequently.
Here is an example of how to use an inline function:
#include <iostream>
using namespace std;
inline int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
int main()
{
cout << "Max of 3 and 4 is: " << max(3, 4) << endl;
return 0;
}
The output of this program will be:
Max of 3 and 4 is: 4
In this example, the max() function is called with the arguments 3 and 4. The compiler expands the function body in place of the function call, resulting in the following code:
if (3 > 4)
cout << "Max of 3 and 4 is: " << 3 << endl;
else
cout << "Max of 3 and 4 is: " << 4 << endl;
Inline functions can be useful for improving the performance of small, frequently called functions. However, you should be careful when using inline functions, as they can increase the size of the program and may not always result in improved performance.