Inline function is one of the important feature of C++. Let's first understand why inline function is used and what is the purpose of inline function?
The main objective behind using function is that code duplication in program is avoided and memory space is saved. If a function is called several times the execution speed of program decreases due to passing of control between caller and callee function. By preventing repetitive calls, program execution speed can be increased. The C++ provides a mechanism called inline function.
When a function is declared as inline, the compiler replaces the function call with corresponding function code i.e., function body is inserted in place of function call during compilation. Passing of control between caller and callee function is avoided.
The inline function is defined as -
inline function-header
{
function body
}
Inline mechanism increases execution performance in terms of speed. The overhead of repetitive function calls and returning values are removed. On the other hand the program using inline functions needs more memory space. If the function is very large in such case inline function is not used because compiler copies the function body that reduces program execution speed. In such case normal function will be more meaningful.
Some of situations where inline function may not work -
1. If inline function is recursive.
2. If function contains static variables.
3. Function containing control structure statement such as switch, if, for loop etc.
4. The function main() can not work as inline.
#include <iostream>
using namespace std;
int cube (int);
int main()
{
int x, y, z=6;
x=
cube(z);
y=
cube(5);
cout << "Value
of x ="<< x <<"\n";
cout << "Value
of y ="<< y <<"\n";
return 0;
}
inline int cube (int a)
{
return (a*a*a);
0 Comments