In this tutorial we wil see the use of inline functions.
It sometimes so happens that we have functions scattered all over the program.In this case a function call causes the program to jumps to the address of the function and come back when the function call terminates. This takes away some precious time.
The above problem can be resolved with the use of inline functions. This causes the compiler to call the code directly from the source. No new memory instruction set is created for the inline function code. This gives the compiler an option to read from the source and there is no need for the call trace to jump around. Thus they are similar to macro definitions and are as fast as macros.
Although the inline declaration in c++ is free and occurs automatically when the function is defined in the declaration, in c it is restricted by the following rules ::
1. In C, any function with internal linkage can be declared inline, but a function with external linkage is has restrictions on inline.
2. If the inline keyword is used in the function declaration, then the function definition should be present in the same translation unit.
Most of the advantage of inline functions comes from avoiding the overhead of calling an actual function. Thus there is a saving of registers and no setting up stack frames. But inline functions present a problem for debuggers and profilers, because the function is expanded at the point of call and loses its identity.
Heres how you can use the inline functions.
The general syntax of using an inline function is :
Code:
inline datatype function_name(arguments)
A general c++ code to square a number would loook like this ::
Code:
#include <iostream.h>
class inline_
{
public:
int square(int);
};
void main()
{
inline_ i1;
int x;
cout <<"\nEnter a number ::";
cin>>x;
cout<<"\n The square is ::" << i1.square(x);
}
int ::square(int x1)
{
return x1*x1;
}
Now using inline functions this would become::
Code:
#include <iostream.h>
class inline_
{
public:
int square(int);
};
void main()
{
inline_ i1;
int x;
cout <<"\nEnter a number ::";
cin>>x;
cout<<"\n The square is ::" << i1.square(x);
}
int inline_::square(int x1)
{
return x1*x1;
}
This code runs upto 30% fastert than a non inline function, the rest depending on the prcessor speed.
Now comes the strategy part. You may use inline functions at your will but keeping in mind that inline functions can take much less time to execute but they have a high memory occupancy on the run. Also the compiler has always an option to overlook your inline declaration if the code declared inline is abnormally large compared to the code size.
Inline declaration although destroys the order of evaluation, does not make the function internal. The function is still external.