It’s not clear to me what benefits there are of declaring your stack variables as constant in C++, I was hoping somebody might explain the benefits and purpose for this technique.
For example:
void func(const std::string& arg)
{
if(someCondition)
{
const std::string foo ("some string plus " + arg);
std::out << foo << std::endl;
someFunction(foo);
// dozens more lines of code...
}
// bla bla bla...
}
Thanks!
1
Yes.
-
It helps the reader to understand your intent. Clearly foo is given an initial value and never changed thereafter.
-
It helps the compiler to optimise your code, for both speed and space. The compiler can perform certain optimisations such as hoisting values out of loops if there is a promise that the value cannot change. This is particularly the case if the value has an alias, which would otherwise defeat optimisation.
-
It occasionally catches bugs, when you accidentally write code to modify something you didn’t mean to.
On the down side, you may not be able to pass the value into a function that takes non-const arguments.
10