In the following C++ functions:
void MyFunction(int age, House &purchased_house)
{
...
}
void MyFunction(const int age, House &purchased_house)
Here are some great articles and a book I found explaining the advantages of using const:
C++ const Correctness
Advice From the C++ Experts: Be Const-Correct
Effective C++ from Scott Meyers
Can I propose the following maxim to you?
If an object/variable can be qualified has being constant, it should be. At worst, it will not cost anything. At best, you will be documenting the role of the object/variable in your code and it will allow the compiler the opportunity to optimize your code even more.
Some compilers neglect to exploit the potential of optimization with the use of 'const' and that has lead many experts to neglect the use of constant parameters by value when it could be used. This practice takes more strictness, but it will not be harmful. At worst, you do not lose anything , but you do not gain anything too and at best, you win from using this approach.
For those who do not seem to understand the utility of a const in a by value parameter of a function/method... here is a short example that explains why:
.cpp
void WriteSequence(int const *, const int);
int main()
{
int Array[] = { 2, 3, 4, 10, 12 };
WriteSequence(Array, 5);
}
#include
using std::cout;
using std::endl;
void WriteSequence(int const *Array, const int MAX)
{
for (int const * i = Array; i != Array + MAX; ++i)
cout << *i << endl;
}
What would had happen if I would had removed the const in front of int MAX and I had written MAX + 1 inside like this?
void WriteSequence(int Array[], int MAX)
{
MAX += MAX;
for (int * i = Array; i != Array + MAX; ++i)
cout << *i << endl;
}
Well your program would crash! Now, why would someone write "MAX += MAX;" ? Perhaps human error, maybe the programmer was not feeling well that day or perhaps the programmer simply did not know how to write C/C++ code. If you would have had const, the code would have not even compiled!
Safe code is good code and it does not cost anything to add "const" when you have it!
Here is an answer from a different post for a very similar question:
"const is pointless when the argument is passed by value since you will not be modifying the caller's object."
Wrong.
It's about self-documenting your code and your assumptions.
If your code has many people working on it and your functions are non-trivial then you should mark "const" any and everything that you can. When writing industrial-strength code, you should always assume that your coworkers are psychopaths trying to get you any way they can (especially since it's often yourself in the future).
Besides, as somebody mentioned earlier, it might help the compiler optimize things a bit (though it's a long shot).
Here is the link: answer.