Switch to full style
C++ code examples
Post a reply

Constant References

Thu Nov 13, 2008 2:17 pm

cpp code
#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.



Post a reply
  Related Posts  to : Constant References
 Boolean type constant     -  
 Functions and References     -  
 References confuse me. How do they differ from pointers?     -  

Topic Tags

C++ Variables