Does it ever make sense to make a fundamental (non-pointer) parameter const?

Posted by Scott Smith on Stack Overflow See other posts from Stack Overflow or by Scott Smith
Published on 2010-03-16T04:34:16Z Indexed on 2010/03/16 5:46 UTC
Read the original article Hit count: 245

I recently had an exchange with another C++ developer about the following use of const:

void Foo(const int bar);

He felt that using const in this way was good practice.

I argued that it does nothing for the caller of the function (since a copy of the argument was going to be passed, there is no additional guarantee of safety with regard to overwrite). In addition, doing this prevents the implementer of Foo from modifying their private copy of the argument. So, it both mandates and advertises an implementation detail.

Not the end of the world, but certainly not something to be recommended as good practice.

I'm curious as to what others think on this issue.

Edit:

OK, I didn't realize that const-ness of the arguments didn't factor into the signature of the function. So, it is possible to mark the arguments as const in the implementation (.cpp), and not in the header (.h) - and the compiler is fine with that. That being the case, I guess the policy should be the same for making local variables const.

One could make the argument that having different looking signatures in the header and source file would confuse others (as it would have confused me). While I try to follow the Principle of Least Astonishment with whatever I write, I guess it's reasonable to expect developers to recognize this as legal and useful.

© Stack Overflow or respective owner

Related posts about c++

Related posts about best-practices