C++ functions: Inline Functions

C++ provides inline functions for improving performance for short functions.

Point Implementing a program using functions makes the program easy to read and easy to main­tain, but function calls involve runtime overhead (i.e., pushing arguments and CPU registers into the stack and transferring control to and from a function). C++ provides inline functions to avoid function calls. Inline functions are not called; rather, the compiler copies the function code in line at the point of each invocation. To specify an inline function, precede the function declaration with the inline keyword, as shown in Listing 6.9.

Listing 6.9 InlineDemo.cpp

1 #include <iostream>
2
using namespace std;
3
4
inline void f(int month, int year)
5 {
6    cout <<
“month is ” << month << endl;
7    cout <<
“year is ” << year << endl;
8 }
9
10
int main()
11 {
12   
int month = 10, year = 2008;
13    f(month, year);
// Invoke inline function
14    f(9, 2010); // Invoke inline function
15
16   
return 0;
17 }

As far as programming is concerned, inline functions are the same as regular functions, except they are preceded with the inline keyword. However, behind the scenes, the C++ compiler expands the inline function call by copying the inline function code. So, Listing 6.9 is essentially equivalent to Listing 6.10.

Listing 6.10 InlineExpandedDemo.cpp

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *