OOPS - [C++ Inline Function]

♠ Posted by Unknown in at 10:11

In-Line Function


We mentioned that functions save memory space because all the calls to the functions cause the same code to be executed; the function body need not be duplicated in memory. 
When the compiler sees a function call, it normally generates a jump to the function. At the end of the function it jumps back to the instruction following the call.

To save execution time in short functions you may elect to put the code in the function body directly in line with the code in the calling program. That is,  each time there’s function call in the source file, the actual code from the function is inserted, instead of a jump to the function.

Characteristics of Inline Function:
  1. Function should be short in length.
  2. Function should not have complex if conditions.
  3. Function should not have loops or recursion.

The disadvantage of in-line functions is that if they are too large and called too often, our program grows larger. For this reason, in general only short functions as declared as in-line functions.

To declare an in-line function, simply precede the function’s definition with the inline specifier. For example, this short program shows how to declare an in-line function.

Example:

#include<iostream.h>
#include<conio.h>
inline int even(int x)
{
 return !(x%2);
}

void main()
{
 int a;
 clrscr();
 cout<<"Enter the Value :";
 cin>>a;
 if(even(a))
            cout<<"The Value is Even....";
 else
            cout<<"The Value is Odd....";
 getch();
}

0 comments:

Post a Comment