Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
The value of an argument that is declared const cannot be changed.
Exercise 5: the many types of const is an exercise about the many types of const.
In function design, consider making read-only arguments const (but note [8] advising against this).
Be suspicious of non-const reference arguments; if you want the function or member function to modify its arguments, use pointers and value return instead [1]. Use const reference arguments when you need to minimize copying of arguments [2].
Use const whenever possible [1-7].
A function (or member function) declaration is the first impression of its body, as it summarizes the effect of the variables involved or produced.
If, for example, you want to calculate the area of a circle (the output) from its ray (the input), you expect the ray not te be modified in the body of the function:
double CalculateCircleArea(const double ray); |
Note that 'double CalculateAreaCircle(const double& ray)' would be correct as well. The guideline is: for easy-to-copy data types, pass by value.
void Swap(int& a, int& b); |
When swapping two values by reference, there will no number be calculated in the process (therefore its a void function. But both variables will/can be changed in the process, therefore the reference operator '&'.
Many newbies do not use const and referencing, yielding code like:
int CalculateSquare(int value); //Incorrect! |
Newbies are easily spotted from their function prototypes. In this function the value of 'value' is copied, squared and returned. Why make a copy? The only reason you WANT a copy is when e.g. using a function that uses referencing or when you temporarily want to modify a copy of a variable:
void PerformMagic(const std::string& s) |
In this case, you just use:
void PerformMagic(std::string s) |
When using pointers, const can be used twice for every argument.
struct MyStruct { int mX; }; |
To indicate that MyStruct is only read from, use Transmogrify1 and Transmogrify3.
Use const whenever possible [1-7].
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.