ES.25 -- Is it truly beneficial to always employ const for objects?
"Yes, certainly!". This was my initial reaction upon encountering the recommendation. However, as I delved deeper into C++ development, engaged in code reviews, and studied existing programs in the language, I started to question whether this recommendation is universally beneficial. Seeking insights from seasoned C++ developers, I discovered that the use of const for local variables is subjective, driven by personal preferences, individual tastes, and even ideological beliefs, rather than being an unequivocally superior practice (in their opinion). Here are a few tips based on these discussions:
-
constcreates a lot of "visual noise" in the code. For example,const int* const pointer = &variable;. This is harder to read thanint * pointer = &variable;. But maybe it makes sense to sacrifice readability for something more significant? - "
constallows you to monitor in the code which variables are changing and which are not." This is justified in large chunks of code (which it is recommended to avoid), where it is problematic to keep track of everything. But is it really worth inflating the amount of code and sacrificing readability in small methods, where it is easy to keep track of the local variables constancy? -
constwon't help optimize the code. Modern compilers themselves are able to do static analysis and optimize constants.
Being a lead programmer, in my team I allowed to write const for local variables at will and no longer pay attention to it in code reviews. The colleagues with whom I discussed this issue have the same opinion. Writing const for local variables is a programmer's personal matter.
What's your opinion?
IMHO: In a language, it is better to have a mutable modifier rather than const. Then this problem did not exist at all. But c++ cannot afford such an approach.
P.S. Something similar was discussed in https://github.com/isocpp/CppCoreGuidelines/issues/19.
there are two exceptions noted in Con.1, at least it should be linked from ES.25
Exceptions in Con.1 are clear, I would also add to them "do not use const for the function's return value of simple type". It is useless to write const int func(). But my issue does not address these exceptions. It's about using const for local variables.