Inline functions in c++
Inline functions
Inline functions are similar to #define macros. This function is a function that is expanded inline when it is invoked. It is easy to make a function inline. Just prefix the keyword inline to the function definition. All inline functions must be defined before they are called.
One of the important advantages of using functions is that they help us save memory space. Imagine a situation where a small function is getting called many times in a program. There are certain overheads involved while calling a function. Time has to be spent on passing values, passing control, returning values and returning control. This is called function call overhead. In C language, we use macros to overcome this disadvantage. Macros don’t really obey the rules of C++ and therefore can introduce problems.
So, C++ uses inline functions. To eliminate the cost of calls to small functions C++ proposes a new feature called inline function.
If an inline function is a member function (MF) of a C++ class, there are couple of ways to write it.
Every time a function is called the following sequence of invisible actions take place:
- It performs goto statement to reach the function
- If a return statement is given, value is returned to the calling program
- Uses keyword inline as a function qualifier
- Function body is copied at each function (inline) call.
Example of inline function
Points on inline function
- An inline function is inserted whenever a call to that function appears. This is called inline expansion. All inline functions must be defined before they are called.
- The significant feature of inline functions is that there is no explicit function call. The function body is inserted at the point of inline function call.
- The constructor functions can also be defined as inline functions
- No need to establish a linkage between the calling function and called function.
- It is advisable to define functions having small body as inline functions.
- Static data is not allowed in inline functions
- Inline functions are not found in C language
Inline disadvantages
- Most of the advantage of inline functions comes from avoiding the overhead of calling an actual function. Such overhead includes saving registers, setting up stack etc. But with large functions the overhead becomes less important.
- The biggest drawback of inline function is prohibition of use of for, while and do-while statements in inline function
- Inline expansion makes a program run faster because the overhead of a function call and return is eliminated. However, it makes the program to take up more memory because the statements that define the inline functions are reproduced at each point where the function is called.