Program Notes

Because the const array object Snames is declared above all the functions, it can be used in any of the following function definitions. Like the const Seasons, Snames is shared by the whole source code file. The program doesn’t have a using directive, so array and string have to be used with the str:: qualifier. To keep the program short and focused on how functions can use objects, the fill() function doesn’t check for valid input.

Both fill() and show() have drawbacks. For show(), the problem is that expenses holds four double values and it’s inefficient to create a new object of that size and to copy the expenses values into it. The problem gets worse if we modify the program to handle expenses on a monthly basis or daily basis and expand expenses accordingly.

The fill() function avoids this inefficiency problem by using a pointer so that the function acts on the original object. But this comes at the cost of notation that makes the programming look more complicated:

fill(&expenses);    // don't forget the &
...
cin >> (*pa)[i];

In the last statement, pa is a pointer to an array<double, 4> object, so *pa is the object, and (*pa)[i] is an element in the object. The parentheses are required because of operator precedence. The logic is straightforward, but results enhance opportunities for making errors.

Using references, as discussed in Chapter 8, helps solve both the efficiency and the notational problems.

Recursion

And now for something completely different. A C++ function has the interesting characteristic that it can call itself. (Unlike C, however, C++ does not let main() call itself.) This ability is termed recursion. Recursion is an important tool in certain types of programming, such as artificial intelligence, but we’ll just take a superficial look (artificial shallowness) at how it works.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.108