------------------------------------------------------------------------------
MC logo
Constant References
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Functional Average] [Functional Average II] [Functional Average III] [Default Parameters] [Function Overloading] [Reference Parameters] [Constant References] [Namespaces] [Namespaces I] [Using Namespaces]
constref.cc
#include <iostream>

using namespace std;

// This simply sets a to a function of b.
void fred(int &a, const int &b)
{
        a = 2 * b * b;

        // This would be illegal:
        //   b = 10;
}

main()
{
        int m;

        fred(m, 17);
        cout << "m = " << m << endl;

        int c = 45;
        fred(m, 2*c + m);
        cout << "m = " << m << endl;
}

The const modifier on a reference parameter means that the function will not change the item referred to.

Note that it is allowed to pass an expression parameter to a const reference, since it will not be assigned.

We'll find more use for this feature later, when we start flinging around things larger than integers and floats.