< previous page page_875 next page >

Page 875
The Print function: The date is to be printed in the form month, day, comma, and year. We need a blank to separate the month and the day, and a comma followed by a blank to separate the day and the year. The month is to be printed in word form rather than as an integer. We set up a local data structure to store the names of the months: a 12-element array of strings containing the names of the months. Remembering that arrays are indexed starting at 0 in C++, we select the appropriate string by using the index [mo-1].
Print ()
Declare monthString to be a 12-element array of strings and
  initialize monthString[0] to January, monthString[1]
  to February, and so forth
Print monthString[mo-1], , day, , , yr

When we implement the Print function in C++, we want to be sure to declare monthString to be static. By default, local variables in C++ are automatic variablesthat is, memory is allocated for them when the function begins execution and is deallocated when the function returns. By declaring monthString to be static, the array is allocated once only, when the program begins execution, and remains allocated until the program terminates. From function call to function call, the computer does not waste time creating and destroying the array. The body of the Print function appears as follows.
{
    static char monthString[12][10] =
    {
         January, February, March, April, May, June,
         July, August, September, October, November,
         December
    };

    cout << monthString[mo1 ] <   < day < ,  < yr;
}
Testing: In testing the Print function, we should print each month at least once. Both the year and the day should be tested at their end points and at several points between.
The ComparedTo function: If we were to compare two dates in our heads, we would look first at the years. If the years were different, we would immediately determine which date came first. If the years were the same, we

 
< previous page page_875 next page >