Skip to main content

4. Write a cpp program which explain the feature of a inline function.

#include <iostream>

using namespace std;

// define an inline function
inline int max(int x, int y)
{
return (x > y) ? x : y;
}

void main()
{
int a = 10, b = 20;

// call the inline function
int m = max(a, b); // m is set to 20

cout << m << endl; // prints 20

return 0;
}

Output

20

In this example, we define an inline function max that returns the maximum of two integers. We use the inline keyword to indicate that the function should be expanded in line with the code that calls it. When the max function is called in the main function, the compiler will replace the function call with the body of the function, resulting in faster code execution.

It's important to note that the use of inline functions is a suggestion to the compiler, and the compiler may choose not to inline a function for various reasons. In general, inline functions are most useful for small, frequently called functions, as the overhead of inlining the function may outweigh the benefits for larger or less frequently called functions.