const
is a type qualifier in C/C++ used to indicate a given variable/method is constant and cannot be changed later in the program. For variables, this sets them as immutable:
When applied to pointers, there are two different ways const
is handled:
- For
const int *p = x
, we can change what it’s pointing to but not change the value inside its address, i.e.,*p = 30
may spit out a compiler error. - For
int *const p
, we can’t modify what it’s pointing to but we can change the value inside the address. Very confusing!
When we take a function input that doesn’t change, we should use a const
for safety — if it doesn’t need to change, then any code we write that changes it will cause a compile-time error (a big hint we’re doing something wrong).
We can also set methods as const
:
In this case, we cannot change any member data. The this
pointer effectively becomes a pointer to a const
object.