TLDR: always put const
AFTER the element you want to specify as constant
We all love const
variables and parameters. They are, well, constant. You're sure they won't be changed by a side-effect of your code (or someone else's).
What you usually see in C++ is something like:
const int myVar(42);
This is pretty clear, right? myVar
is stores an integer, 42 in this case, and this value won't change until we get out of the current scope. So if we put something like:
const int myVar(42);
myVar++;
your compiler will yell at you with something like error: increment of read-only variable ‘myVar’
.
So far so good. But I once again stumbled across an issue using const
that I, even with my 10+ years of experience, still haven't stuck in my head (but I hope that writing this down will help so I'll guess I should share it).
Let's say you want to declare a constant pointer to an integer. The no-brainer line of code that gets out is:
const int *myVarPtr;
Following the same logic as before, if I try to modify it:
int myVar(42);
const int *myVarPtr;
myVarPtr++;
the compiler doesn't complain! And it's normal because, if you stick to its definition, const
applies to the element to its left, unless it's the first element. Then it applies to its right.
So what we declared earlier was actually a non-const pointer to a const integer. The original goal would be achieved with this code:
int * const myVarPtr;
I hate exceptions. This is the typical case where the exception makes the concept confusing. Now I just make sure I'm never in this case.
If you have only one thing to learn from this article it would be this: always put const
AFTER the element you want to specify as constant.
I totally agree, by placing the const on the right side we can read from right to left: