Sams Teach Yourself C++ in 21 Days

(singke) #1
Organizing into Functions 121

5


59:
60: double Double(double original)
61: {
62: cout << “In Double(double)\n”;
63: return 2 * original;
64: }

myInt: 6500
myLong: 65000
myFloat: 6.5
myDouble: 6.5e+20
In Double(int)
In Double(long)
In Double(float)
In Double(double)
DoubledInt: 13000
DoubledLong: 130000
DoubledFloat: 13
DoubledDouble: 1.3e+21
The Double()function is overloaded with int,long,float, and double. The
prototypes are on lines 5–8, and the definitions are on lines 42–64.
Note that in this example, the statement using namespace std;has been added on line
10, outside of any particular function. This makes the statement global to this file, and
thus the namespace is used in all the functions declared within this file.
In the body of the main program, eight local variables are declared. On lines 14–17, four
of the values are initialized, and on lines 29–32, the other four are assigned the results of
passing the first four to the Double()function. Note that when Double()is called, the
calling function does not distinguish which one to call; it just passes in an argument, and
the correct one is invoked.
The compiler examines the arguments and chooses which of the four Double()functions
to call. The output reveals that each of the four was called in turn, as you would expect.

Special Topics About Functions ..........................................................................


Because functions are so central to programming, a few special topics arise that might be
of interest when you confront unusual problems. Used wisely, inline functions can help
you squeak out that last bit of performance. Function recursion is one of those wonder-
ful, esoteric bits of programming, which, every once in a while, can cut through a thorny
problem otherwise not easily solved.

OUTPUT


LISTING5.8 continued


ANALYSIS
Free download pdf