7.6. Inline Functions
Recall the function we wrote on page 248 that returned a reference to the shorter of its two string parameters:
The benefits of defining a function for such a small operation include:It is easier to read and understand a call to shorterString than it would be to read and interpret an expression that used the equivalent conditional expression in place of the function call.If a change needs to be made, it is easier to change the function than to find and change every occurrence of the equivalent expression.Using a function ensures uniform behavior. Each test is guaranteed to be implemented in the same manner.The function can be reused rather than rewritten for other applications.
// find longer of two strings
const string &shorterString(const string &s1, const string &s2)
{
return s1.size() < s2.size() ? s1 : s2;
}
There is, however, one potential drawback to making shorterString a function: Calling a function is slower than evaluating the equivalent expression. On most machines, a function call does a lot of work: registers are saved before the call and restored after the return; the arguments are copied; and the program branches to a new location.
inline Functions Avoid Function Call Overhead
A function specified as inline (usually) is expanded "in line" at each point in the program in which it is invoked. Assuming we made shorterString an inline function, then this call
would be expanded during compilation into something like
cout << shorterString(s1, s2) << endl;
The run-time overhead of making shorterString a function is thus removed.We can define shorterString as an inline function by specifying the keyword inline before the function's return type:
cout << (s1.size() < s2.size() ? s1 : s2)
<< endl;
// inline version: find longer of two strings
inline const string &
shorterString(const string &s1, const string &s2)
{
return s1.size() < s2.size() ? s1 : s2;
}

Put inline Functions in Header Files


Exercises Section 7.6
Exercise 7.29:Which one of the following declarations and definitions would you put in a header? In a program text file? Explain why.
235 as an inline function.
(a) inline bool eq(const BigInt&, const BigInt&) {...}
(b) void putValues(int *arr, int size);