What is inline function? - C++

What is inline function?

- An inline function is a combination of macro & function. At the time of declaration or definition, function name is preceded by word inline.
- When inline functions are used, the overhead of function call is eliminated. Instead, the executable statements of the function are copied at the place of each function call. This is done by the compiler.
- Consider the following example :
#include <iostream>
using namespace std;

inline int sqr(int x)
{
   int y;
   y = x * x;
   return y;
}
int main()
{
   int a =3, b;
   b = sqr(a);
   cout <<b;
   return 0;
}
- Here, the statement b = sqr(a) is a function call to sqr(). But since we have declared it as inline, the compiler replaces the statement with the executable statement of the function (b = a *a)
- Please note that, inline is a request to the compiler. If it is very complicated function, compiler may not be able to convert it to inline. Then it will remain as it is. E.g. Recursive function, function containing static variable, function containing return statement or loop or goto or switch statements are not made inline even if we declare them so.
- Also, small functions which are defined inside a class (ie their code is written inside the class) are taken as inline by the compiler even if we don’t explicitly declare them so. They are called auto inline functions.

Define Inline Function.

- When the function is defined Inline, the C++ compiler puts the function body inside the calling function. You can define function as Inline when the function body is small and need to be called many times, thus reduces the overhead in calling a function like passing values, passing control, returning values, returning control.
Difference between inline functions and macros - C++
Difference between inline functions and macros - A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro.....
What are static member functions?
What are static member functions? - A static function can have an access to only other static members (functions or variables) declared in the same class......
Do inline functions improve performance? - C++
Do inline functions improve performance? - Inline functions behave like macros. When an inline function gets called, instead of transferring the control.....
Post your comment
Discussion Board
inline function
when code lines are less we define function inside the class is a inline function.
*helps to reduce the size of function
*remove function call overhead
*works similar as #define in "C".
harvinder 03-18-2012