website logo

What is inline function

Inline function is a function that's mainly defined in one or two line and start with keyword inline. when inline function called compiler replace function call with function body. if functions definitions are too long or complicated then compiler treated those inline function as a normal function.


Definition of inline functions:
inline function-header
{
function body
}

Example
inline int sum(int a , int b)
{
return(a+b);
}

inline function sum can be invoked by:
c= sum(4,5);
k=sum(7,8);

with inline function program run faster in comparision normal function because overhead of function call and return is eliminated. function call replace with function body.

inline function may not work if :
if function contain static variables in function defnition.
if inline function are recursive function.
if inline function contain loop(for loop, while loop, do while etc) or switch statement or goto statement.

Inline Function Example

#include <iostream>
inline int add(int a, int b)
{
return(a+b);
}
inline int multiply(int m, int n)
{
return(m*n);
}
inline double divide(double x, double z)
{
return(x/z);
}
int main()
{
int a=4,b=6,m=7,n=4;
float x=4.5,z=3.5;
cout <<add(a,b) << "\n"; // function call replace with function body
cout <<divide(x,z) << "\n";
cout <<multiply(m,n) << "\n";
return 0;
}
output of this program would be
10
1.28
28