51. Inline function

Inline functions are an imperative feature of C++ and are frequently used with classes. Inline functions are functions where the call is made to inline functions. The actual code then gets placed in the calling program. In a program when we call a function the program jumps to the address of the function and when it reaches the end of the function it comes back. This jumping actually involves much more and takes time. But when an inline function is called the compiler will replace the call with the function code. So in reality in that place there will be no function call, only the code of the function. No jumping needed to different addresses. The general format of inline function is as follows:

inline datatype function_name(arguments)

Example:
The following code creates and calls an inline function:
#include<iostream.h>
inline int average(int a, int b)
{
   return (a + b) / 2;
}
void main()

{
   int result = average(12, 14);

   cout << "The average of number 12, 14 is " << result << "\n";
   getch();

}
It is most important to know that the inline specifies is a request, not a command, to the compiler. If, for various reasons, the compiler is unable to fulfill the request, the function is compiled as a normal function.

No comments:

Post a Comment

free counters