Implementing a program as a set of functions is good from a software engineering standpoint, but function calls involve execution-time overhead. C++ provides inline functions to help reduce function call overhead. Placing the qualifier inline before a function’s return type in the function definition advises the compiler to generate a copy of the function’s body code in every place where the function is called (when appropriate) to avoid a function call. This often makes the program larger. The compiler can ignore the inline
qualifier and generally does so for all but the smallest functions. Reusable inline
functions are typically placed in headers, so that their definitions can be included in each source file that uses them.
Software Engineering Observation 6.8
If you change the definition of an inline function, you should recompile all of that function’s clients.
Performance Tip 6.4
Compilers can inline code for which you have not explicitly used the inline keyword. Today’s optimizing compilers are so sophisticated that it’s best to leave inlining decisions to the compiler.
Figure 6.18 uses inline
function cube
(lines 9–12) to calculate the volume of a cube. Keyword const in function cube
’s parameter list (line 9) tells the compiler that the function does not modify variable side
. This ensures that side
’s value is not changed by the function during the calculation. (Keyword const
is discussed in detail in Chapters 7–9.)
1 // Fig. 6.18: fig06_18.cpp
2 // inline function that calculates the volume of a cube.
3 #include <iostream>
4 using namespace std;
5
6 // Definition of inline function cube. Definition of function appears
7 // before function is called, so a function prototype is not required.
8 // First line of function definition acts as the prototype.
9 inline double cube( const double side )
10 {
11 return side * side * side; // calculate cube
12 } // end function cube
13
14 int main()
15 {
16 double sideValue; // stores value entered by user
17 cout << "Enter the side length of your cube: ";
18 cin >> sideValue; // read value from user
19
20 // calculate cube of sideValue and display result
21 cout << "Volume of cube with side "
22 << sideValue << " is " << cube( sideValue ) << endl;
23 } // end main
Enter the side length of your cube: 3.5
Volume of cube with side 3.5 is 42.875
Software Engineering Observation 6.9
The const qualifier should be used to enforce the principle of least privilege. Using the principle of least privilege to properly design software can greatly reduce debugging time and improper side effects and can make a program easier to modify and maintain.