Sams Teach Yourself C in 21 Days

(singke) #1
The C++ Programming Language 659

BD2


don’t spend this time going to and from the function because the function’s code is
placed directly in the listing. The tradeoff for this speed is program size. The code for the
function is duplicated in each place it is called. This means if you call an inline function
15 times, there will be 15 copies of the function’s code in your listing. Listing B2.6 pre-
sents a listing using inline functions.

LISTINGB2.6 inline.cpp. Using an inline function
1: //Using inline functions
2: #include <iostream.h>
3:
4: inline long square( long value )
5: {
6: return (value * value );
7: }
8:
9: inline long halve( long value )
10: {
11: return (value / 2);
12: }
13:
14: int main(int argc, char* argv[])
15: {
16: long nbr;
17:
18: cout <<”\nEnter a number: “;
19: cin >> nbr;
20:
21: cout <<”\n\nSquared: “ << square(nbr);
22: cout <<”\nHalved: “ << halve(nbr);
23:
24: cout <<”\nHalf the square: “;
25: cout << halve(square(nbr));
26:
27: cout << “\n\nDone!”;
28:
29: return 0;
30: }

Enter a number: 16

Squared: 256
Halved: 8
Half the square: 128

Done!

OUTPUT

37 448201x-Bonus2 8/13/02 11:18 AM Page 659

Free download pdf