A quick explanation of how const and constexpr work on pointers inÂ C++
So I was checking that my knowledge was correct when working on a Firefox bug.
I made a quick C++ file with all the examples I know of how to use const and constexpr on pointers.
As one can see, its pretty confusing!
Because there are several places in a statement where you can put â€˜constâ€™ it can be complicated to work out what part of your statement the â€˜constâ€™ is referring too.
Generally, its best to read from right to left to work it out.Â i.e:
static const char * const hello;
Would readÂ like:
hello (is a) const pointer (to) const char
But, that takes a bit of practice.
C++â€™s constexpr brings another new dimension to the problem too!
It behaves like const in the sense that it makes all pointers constant pointers.
But because it occurs at the start of your statement (rather than after the â€˜*â€™) its not immediately obvious.
Heres my list of all the ways you can use const and constexpr on pointers and how theyÂ behave.