The const Parameter Modifier

  1. We have used the const modifier to ensure that certain class member functions cannot change the state of the class.

  2. The const modifier can also be used with any function parameters to tell the compiler that the values of those parameters cannot be changed by the function.

  3. The compiler will issue a warning message when the function attempts to change the value of a parameter that is protected by the const modifier.

  4. It is especially important to use the const modifier to protect certain arrays from having the function inadvertently change some of its elements.

  5. The const modifier is an all or nothing proposition. If it is used for one array parameter of a particular type, then it should be used for every other array parameter that has that type and that is not changed by the function. The reason has to do with function calls within function calls.

  6. Consider the definition of the function show_difference, which is given below along with the prototype of a function used in the definition:

    double compute_average(int a[ ], int number_used);
    //Returns the average of the elements in the first number_used
    //elements of the array a. The array a is unchanged.

    void show_difference(const int a[ ], int number_used)
    {
        double average = compute_average(a, number_used);
        cout << "Average of the " << number_used << " numbers = "
                  << average << endl << "The numbers are:\n";
        for (int n = 0; n < number_used; n++)
            cout << a[n] << " differs from average by " << (a[n] - average) << endl;
    }

    Most compiler will issue an error message or warning message because although the function show_difference cannot change its parameter a, it calls the function compute_average which might change the value of its parameter a. The cure is to use the const modifier for the function compute_average also, as shown below:

    double compute_average(const int a[ ], int number_used);