(const char)*
or const (char*)?
i.e. is it a pointer to a char but the memory address it points to is const, or is it a variable pointer that points to a const char. (const char)*
or const (char*)?
i.e. is it a pointer to a char but the memory address it points to is const, or is it a variable pointer that points to a const char. Read the pointer declarations right-to-left.
* const X* p means “p points to an X that is const”: the X object can’t be changed via p.
* X* const p means “p is a const pointer to an X that is non-const”: you can’t change the pointer p itself, but you can change the X object via p.
* const X* const p means “p is a const pointer to an X that is const”: you can’t change the pointer p itself, nor can you change the X object via p.
And, oh yea, did I mention to read your pointer declarations right-to-left?
https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-p...char* const
const char* const f() const
is the best! const char *
and char * const
are obvious (whichever the const keyword is closest to).That rule of thumb doesn't work though for
char const *
or char * const *
though.Oof no I HATE this.
I also hate it when people write
char *a;
because the type is char* (i.e. pointer to a char) and the name of the variable is a.In the first, the variable `a` is const, but `*a` is not const. That is, you cannot change the value of `a` but you can change what it points to.
In the second `a` is not const, but `*a` is. That is, you can change `a` but you cannot change the value it points to.
I feel that your confusion is tied up in not understanding how C and C++ type declarations work, as is your insistence on `char* a`.
Dennis Ritchie (the C language designer) intended it to be written as `char *a` and talked about this at length over the years as an important design decision: variable declaration follows _usage_, so it’s `char *a` because the type of `*a` is `char`.
For better or worse, Stroustrup took this design decision into C++.
Sure both will parse in this simple case, but keeping this in mind is also the way that more complex declarations make sense.
But it's not.
char *a, b;
The type you are assigning is just char. The * only affects a.