Recently, I have been developing a practice of making many things in my code as const:
(1) Arguments to function, which I know never going to be changed. e.g.:
void foo (const int i, const string s)
^^^^^ ^^^^^
(2) Return types as const. e.g.:
struct A {
...
const int foo () { return ...; }
^^^^^
operator const bool () const { return ...; }
^^^^^
};
(3) Trivial computation of integer or strings. e.g.:
const uint size = vec.size();
^^^^^
const string s2 = s1 + "hello ";
^^^^^
… and few more places. Typically in other real world codes, I don’t see such small scale variables marked as const. But I thought, making them const will never harm. Is it a good programming practice ?
(1) and (3) are closely related. A by-value parameter is just a local variable with that name, as is the result of your computation.
Usually it makes little difference in short functions whether you mark local variables
constor not, since you can see their entire scope right in front of you. You can see whether or not the value changes, you don’t need or want the compiler to enforce it.Occasionally it does help, however, since it protects you from accidentally passing them to a function that takes its parameter by non-const reference, without realising that you’re modifying your variable. So if you pass the variable as a function argument during its life, then marking it
constcan give you more confidence that you know what value it has afterwards.Very occasionally, marking a variable
constcan help the optimizer, since you’re telling it that the object is never modified, and sometimes that’s true but the compiler can’t otherwise prove it. But it’s probably not worth doing it for that reason, because in most cases it makes no difference.(2) is another matter. For built-in types it makes no difference, as others have explained. For class types, do not return by const value. It might seem like a good idea, in that it prevents the user writing something pointless like
func_returning_a_string() += " extra text";. But it also prevents something which is pointful — C++11 move semantics. Iffooreturns a const string, and I writestd::string s = "foo"; if (condition) s = foo();, then I get copy assignment ats = foo();. Iffooreturns a non-const string then I get move assignment.Similarly in C++03, which doesn’t have move semantics, it prevents the trick known as “swaptimization” – with a non-const return value I can write
foo().swap(s);instead ofs = foo();.