11

These last weeks, I found myself using a lot of const everywhere. Not only in methods or arguments declarations, but even for temporary variables.

Let me illustrate with a simple function.

I used to write:

// A dummy function that sums some computation results unsigned int sum_results(const Operation& p1, const Operation& p2) { unsigned int result1 = p1.computeResult(); unsigned int result2 = p2.computeResult(); // Well this function could be in one single line but // assume it does more complex operations return result1 + result2; } 

But now it is more like:

// A dummy function that sums some computation results unsigned int sum_results(const Operation& p1, const Operation& p2) { const unsigned int result1 = p1.computeResult(); const unsigned int result2 = p2.computeResult(); // Well this function could be in one single line but // assume it does more complex operations return result1 + result2; } 

The latter makes more sense to me and seems less error prone. (I admit that in this example, it doesn't really matter) However I've seen very few code samples where const was used on temporary/local variables. And I'd like to understand why.

Is there any reason why this isn't a common case ? Am I abusing with my use of const ? Or is it just me that has been looking at the wrong samples ?

1
  • int in unsigned int provides no new or useful information, you should remove unnecessary noise. Commented Jan 3, 2020 at 16:31

7 Answers 7

23

Using const on local variables improves code clarity, so it's a good idea. You see const and you immediately know that the variable is never changed later in scope. It's from the same series as making functions short and returning early.

Developers are lazy - they often think that it's a useless word that doesn't change anything. IMO they are wrong.

Sign up to request clarification or add additional context in comments.

4 Comments

+1. Putting const on local variables that are not going to change (or shouldn't change) catches errors before they happen (at compile time) and clearly shows your intent to the next programmer that has to look at your code.
But would it lead to better perfomance or a better optimization by the compiler.
@DumbCoder: Maybe, but highly unlikely. Modern compilers are very good at optimizing code. If one really cares, they should try both and inspect the emitted machine code.
@DumbCoder: extremely unlikely, both CLang and gcc are using SSA representations and thus know if a variable is ever changed, or not. However it indicates the intent to the compiler, so that later trying to access it provokes an error and forces the developer to think about whether or not it's appropriate.
5

This is effectively the same reason why assertions are rarely used. const on interfaces is mandatory, const in the implementation is voluntary. Programmers are lazy.

Edit: just in case it isn't clear, your approach is better.

Comments

5

I would personally say that there never are too many const, and I use them abundantly for local variables. The only context where I could add a const but don't is on parameters of built-in types :

void foo(const int);

Here, I believe (but that's a matter of personal taste really) that it uselessly clutters the interface.

Comments

3

I don't think it's purely a case of programmers being lazy - concision is also a consideration. Some people may find int x; less mental load than "const int x;" when reviewing the functions: that bit extra space might help them fit a comment alongside. I mention that not as a recommendation, but because I think it's important to understand all the "costs" that factor into peoples' attitudes, as it really is confusing that people don't consistently use const here.

It's also interesting to consider that at some point in using a variable in a function, it may become necessary to tweak it. For example, you calculate something, but then you go into a few if statements and things and there's some edge case where you need to remove a trailing element from a string, handle an off-by-one issue, clear the value etc.. If you had initially made the variable const, then your workflow is interrupted more to return to and remove const from the definition, then return the cursor to where you're working. Countering this, a habit of using const where possible is a red flag that some such tweaks are hidden in the function body, and very useful for later understanding and maintenance.

Still, I actively encourage you to continue to use const: I typically do so and consider it best practice. The reasons for that are obviously understood by you, and have been enumerated in other answers.

Comments

1

In C++, this is a good approach to constify variables if you can. But having said this, this makes more sense in the cases where a variable is either being passed over as an argument or it is shared between different pieces of code (like class variables). The main idea is to stop accidental modification of variables by other code which doesn't know that this variable is not meant to be changed.

Therefore, in light of the above, for variables local to a function, constifying them is a sort of overkill. However, doing this doesn't harm anything.

Comments

1

There's nothing wrong with doing that, but you use const to enlist the compiler in helping you enforce a constraint, when you know an object shouldn't be modified. If you don't care if the object is modified, than it's superfluous.

2 Comments

Even if this dummy example, nor result1 or result2 are meant to be modified. They hold a value that shouldn't change. I don't mind having more keystrokes whenever I can make my code less error-prone.
"nor result1 or result2 are meant to be modified. They hold a value that shouldn't change" Then they should be const. My point is only that you do it for a reason, and if you're aware of that reason you won't feel like you're abusing anything.
0

In my humble opinion you should take advantage of a strongly-typed language's compiler at every opportunity. I use const for temporary, local variables, immutable references, etc.

The Const Correctness C++ FAQ might have more useful information.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.