Sams Teach Yourself C++ in 21 Days

(singke) #1
Organizing into Functions 123

5


LISTING5.9 A Demonstration of an Inline Function


1: // Listing 5.9 - demonstrates inline functions
2: #include <iostream>
3:
4: inline int Double(int);
5:
6: int main()
7: {
8: int target;
9: using std::cout;
10: using std::cin;
11: using std::endl;
12:
13: cout << “Enter a number to work with: “;
14: cin >> target;
15: cout << “\n”;
16:
17: target = Double(target);
18: cout << “Target: “ << target << endl;
19:
20: target = Double(target);
21: cout << “Target: “ << target << endl;
22:
23: target = Double(target);
24: cout << “Target: “ << target << endl;
25: return 0;
26: }
27:
28: int Double(int target)
29: {
30: return 2*target;
31: }

Enter a number to work with: 20

Target: 40
Target: 80
Target: 160
On line 4,Double()is declared to be an inline function taking an intparameter
and returning an int. The declaration is just like any other prototype except that
the keyword inlineis prepended just before the return value.
This compiles into code that is the same as if you had written the following:
target = 2 * target;
everywhere you entered
target = Double(target);

OUTPUT


ANALYSIS
Free download pdf