Function execution involves the ove rhead of jumping to and from the calling statement. Trading of this overhead in execution time is considerably large whenever a function is small, and hence is such cases, inline functions can be used. A function in C++ can be treated as a macro if the keyword inline precedes its definition.
The syntax is
Inline return_type function_name(parameters)
{
body of the function
}
The significant feature of inline functions is that there is no explicit function call, the function body is substituted at the point of inline function call. Thereby, the runtime overhead for function linkage mechanism is reduced. Sample program
#inlcude <iostream.h>
inline float square(float x)
{
return(x*x);
}
void main()
{
float num;
cout<<”Enter the Number”;
cin>>num;
cout<<”its square is”<<square(num);
}
Member functions defined inside a class are considered as inline functions by default thus, offering both advantages and limitations of inline functions. However in some implementations, member functions having loop instructions such as for, while, do..while, etc., are not treated as inline functions.
Conditions for inline functions
? For functions returning values, if a loop, a switch, or a goto exists
? For functions not returning values, if a return statement exists.
? If functions contain static variables.
? If inline functions are recursive.
When to use Inline functions
? In general, inline functions should not be used.
? Defining inline functions can be considered once a fully developed and tested program runs too slowly and shows bottlenecks in certain functions.
? Inline functions can be used when member functions consist of one very simple statement such as the return statement.
? It is only useful to implement an inline function if the time spent during a function call is more compared to the function body execution time.
Outside function as Inline
C++ treats all the member functions that are defined within a class as inline functions and those defined outside as non-inline. Member function declared outside the class declaration can be made inline by prefixing the inline to its definition as show below.
Inline return_type Class_Name :: function_name(arguments)
{
function body;
}
Sample Program
#include <iostream.h>
class date
{
int d,m,y;
public:
void set(void);
void show(void);
};
inline void date::set(int a, int b, int c)
{
d = a;
m =b;
y = c;
}
inline void date::show(void)
{
cout<<d<<”-“<<m<<”-“<<y<<endl;
}
void main()
{
data d1;
d1.set(27,12,1977);
d1.show();
}
No comments:
Post a Comment