C++ and CONST
const in C++
It's mostly found when declaring a variable something like const int a = 3;
However, it is a sort of "promise" for human being since it will usually not make a difference in the compiled code.
Just as we can break a "promise" sometimes, there is also a workaround to modify const
variable.
const variable
It's self-explanatory. We know what it means when we see it.
const int a = 3;
// illegal
// a = 5;
const with pointer
This is when the most confusing part because there are following variations
const int* a;
int* const a;
int const* a;
const int* const a;
what I would like to think is that const
decorate something that is in its left. For example,
int const *
meansint
is constant becauseint
is in the left.
If there is nothing in its left, const
looks for its right side.
const int *
means the same as above.int
is constant notint*
Then it's fairly easy.
// int is constant
// content cannot be changed
const int* a;
// ok (can be assigned to another pointer)
a = nullptr;
// `const` decorate `*`
// pointer cannot be re assigned
int* const a = new int;
// But, this is ok
*a = 33;
// not ok
// a = nullptr;
// `const` decorate `int`
// it's same as `const int* a`
int const* a = new int;