3 ms·
I think const char * and char * const are obvious (whichever the const keyword is closest to). That rule of thumb doesn't work though for char
by ndesaulniers 3y ago
I think
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.
- dheera 3y ago> char * const 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.
- moregrist 3y ago`char * const a` is a different type from `const char *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.
- Dylan16807 3y ago> because the type is char* (i.e. pointer to a char) and the name of the variable is a. But it's not. char *a, b; The type you are assigning is just char. The * only affects a.
- eMSF 3y agoA lot of folks write char const * (and T const& in C++), and the "rule of thumb" is to read the declaration right to left. In this case, pointer (to) const char. Works also with multiple consts or levels of indirection.