C++ – Should ‘const’ Be Used in Parameters and Local Variables?

ccoding-styleconst

This question is inspired by a question about final in
java
.

In C/C++, should I use const whenever possible?

I know there is already a related question about using const in parameters. Unfortunately that question and it's answers don't fully answer my question, because it's only about function parameters, but I would also like to know about other cases (eg: local variables).

Also, almost all answers to that question say we should use const because it contains useful information about the accessibility of variables. But this seems to conflict with an answer about using final in Java which states final may be superfluous if it doesn't contain extra information and so it should be omitted to keep the code short and clean.

So, should I use const whenever possible? If so, why is the advice for const in C++ different from the advice for final in Java?

Best Answer

First of all, since you referenced Java's final, that is a totally different beast than const. Final means the reference cannot change, but says nothing about mutability. Const goes further by saying "a const reference cannot mutate" which is a much stronger guarantee. To do this in Java, internal state must be final and determined at construction time. Const is a lot easier to use, and an existing object can be "promoted" into a const reference.

Yes, you should use const whenever possible. It makes a contract that your code will not change something. Remember, a non-const variable can be passed in to a function that accepts a const parameter. You can always add const, but not take it away (not without a const cast which is a really bad idea).

Const-correctness may be tedious at times, but it helps guarantee immutability. This is crucial in multi-threaded code where threads share objects. It makes certain tasks more efficient: instead of copying state, just reuse the same immutable object. Libraries might accept const parameters in order to provide a guarantee to the programmer that no, your object will not change in an unpredictable way in the black hole that is the library's guts.