Last Update:
Please Declare Your Variables as Const
Table of Contents
I must confess that, over the last few years, I’ve become somewhat obsessed with the idea of making all variables const
. Whenever I declare a variable within a function body, I consider whether I can make it constant. Here’s why I believe you should adopt the same approach.
I wrote this blog post in 2016 and refreshed it in 2023. It presents a somewhat relaxed view of const
and offers improved guidelines. See a followup about const, move and RVO.
What’s wrong?
What’s wrong with the following code?
int myVariable = 0;
// some code...
myVariable = ComputeFactor(params...);
Versus:
// some code...
const int myVariable = ComputeFactor(params...);
In the first sample, we’re just changing the value of a variable, but in the second snippet, we have an immutable state.
Let’s go through the list of benefits of the second approach.
Please note that I’ll focus only on variables used in function bodies, not parameters of functions, or class members.
Why it helps
Performance?
Several years ago, my colleague suggested using const
for variables. I thought the only reason for this was optimization and performance. Later, I understood that it’s not obvious, and there are far more important reasons for using const
.
In fact, a good C++ compiler can do the same kind of optimization whether you use const
or not. The compiler will deduce if a variable is changed or just initialized once at the start. So, is there any performance benefit here?
It’s hard to show real numbers here. Ideally, we could get a C++ project (let’s say minimum 10k LOC) and then use const
whenever possible, and compare it against the same project without const
.
In a synthetic, small example like:
string str;
str = "Hello World";
vs
const string str = "Hello World";
There can be a performance increase of even 30%! Numbers from J. Turner talk “Practical Performance Practices”. As one commenter noticed: the gain comes not from the const itself but from the fact that we’re not reassigning the value.
As we can see, there’s potential to gain some performance, but I wouldn’t expect much across the whole project. It depends on the context. Maybe something like 1…or 2% max. As usual: measure, measure, measure! :)
Still, why not make life much easier for the compiler and have better code.
So, it seems that “performance” is not the strongest reason for using const
. Read on for far more important aspects:
Variables are declared local to their use
To declare a constant variable, you must have all the required data. That means you cannot just declare it at the beginning of a function (like in the standard old C-way). Thus, there’s a higher chance of having variables entirely local to their usage.
void foo(int param)
{
const int otherVariable = Compute(param);
// code...
// myVar cannot be declared before 'otherVariable'
const int myVar = param * otherVariable;
}
Declaring variables local to their use is not only a good practice but can result in less memory usage (since not all variables might be allocated) and even safer code.
Clear Intent
When you declare something as constant, you make it clear “I won’t change the value of that variable.”
Such a practice is vital when you read the code. For example:
int myVar = 0;
// code...
// code...
When you see such a thing, you’re not sure if myVar
will change or
not. It might not be a problem in small functions, but what about
longer, complex methods?
While having:
const int myVar = ...;
// code...
You’re at least sure that nothing happens with myVar
. You get one parameter less to track.
Clean Code
Sometimes the initialization of a variable won’t be just a simple assignment. Several lines (or more) might be used to give a proper value. In that case making the variable const
will force you to move such initialization to a separate place.
As I described in IIFE for Complex Initialization you might enclose the initialization in IIFE or a different method.
Anyway, you’ll avoid code looking like this:
int myVariable = 0;
// code...
// complex initialization of 'myVariable'
if (bCondition)
myVariable = bCond ? computeFunc(inputParam) : 0;
else
myVariable = inputParam * 2;
// more code of the current function...
No matter what you use, you’ll end up with only one place where the variable gets its value.
Fewer bugs
When a variable is const
you cannot change it, so some unwanted bugs are less likely to occur.
Accidental problems might easily happen when there’s some long function and variables tend to be reused in some cases. You change the value of a variable, and it works for your case, but the old case where it was used now stops working. Again, declaring a variable as const
will at least protect you from such stupid bugs. Not to mention that debugging such errors might be a real pain.
BTW: for an example please see this blog posts from Andrzej Krzemienski: More const — fewer bugs
Moving towards functional languages
Functional style is probably a topic worth a separate article, but in general having immutable objects is an essential thing in functional languages.
Immutable objects are thread safe by their nature. When a thread processes those kinds of objects, we can be sure that no other threads are changing the objects. Lots of data races can be avoided. That opens many ways to parallelize the algorithm relatively easy.
Because others says so
From C++ Core Guidelines (Con: Constants and Immutability)
Con.1: By default, make objects immutable
Reason: Immutable objects are easier to reason about, so make object non-const only when there is a need to change their value. Prevents accidental or hard-to-notice change of value.
And
Con.4: Use const to define objects with values that do not change after construction
Reason: Prevent surprises from unexpectedly changed object values.
From Effective C++ by Scott Meyers (chapter 3):
Use const whenever possible.
The wonderful thing about const is that it allows you to specify a semantic constraint - a particular object should not be modified and compilers will enforce that constraint. It allows you to communicate to both compilers and other programmers that a value should remain invariant. Whenever that is true, you should be sure to say so, because that way you enlist your compilers’ aid in making sure the constraint isn’t violated.
Jason Turner:
- CppCon 2016: “Rich Code for Tiny Computers: A Simple Commodore 64 Game in C++17”
- Practical Performance Practices
Exceptions
‘A constant variable’ isn’t that an oxymoron?
Of course, there are situations where a variable needs to be a ‘normal.’ In fact, you might argue that most cases involve the need to modify a value. So unless you’re trying to write functional code (that likes immutability), you’ll end up with tons of examples when you need to change a value (or just part of an object).
Simple examples: calculating a sum of an array, iterators, small functions, changing health param in GameActor, setting a part of GPU pipeline.
Still, bear in mind that the most of the above examples could be rewritten into an ‘immutable’ version as well. For example, you can use higher-order functions like Fold/Reduce, and recursion to implement many ‘standard’ algorithms. But that’s going into functional languages area.
One remark: while I was writing this article I realized that I make a distinction here: variables vs. larger objects. In theory, those are the same, but for practical reasons, it’s easier to use const
on smaller, ‘atomic’ types. So, I try to use const
for smaller types: like numerics, strings, Vector2d, etc… but when I have some large custom class, I just skip const
and allow to mutate its state (if needed). Maybe in my next iteration of my ‘const correctness’ I’ll try to apply that rule to larger objects as well… so this would be a more functional style of programming.
Summary
I hope after reading this post, you’ll at least try using const
variables more often. It’s not about being 100% const
every time, but it’s important to see the benefits of this approach.
As I’ve described, the resulting code will be more verbose, explicit, cleaner (with probably smaller functions) and safer. Not to mention that you’ll get additional help from the compiler.
Please also have a look at this cool summary from Arthur O’Dwyer: `const` all the things?.
And a followup article about Const, move and RVO.
Back to you
- Do you
const
variables when possible? - Does your project guideline mention
const
correctness?
I've prepared a valuable bonus for you!
Learn all major features of recent C++ Standards on my Reference Cards!
Check it out here: