Most of the time I see constant C-strings defined as:
static char const* MY_CONSTANT = "Hello World";
However, the pointer itself is not const
. Wouldn't it be more appropriate to do it like below?
static char const* const MY_CONSTANT = "Hello World";
There are 2 goals with constant globals like this, I think:
- Do not allow modification of the string
- Do not allow the variable to point to anything else
I simply assumed these 2 goals were needed when defining constant strings.
Another interesting thing is that I am allowed to do this:
int main()
{
auto MY_CONSTANT = "";
MY_CONSTANT = "Another String";
}
This tells me that auto
deduces the string as char const*
and not char const* const
.
So I have two main questions:
- What is the most appropriate way to define constant c-style strings (I suppose constant pointers-to-something, is the more general question?). Why do you choose one or the other?
- Concerning my example with
auto
, it makes sense why it chooseschar const*
(because it's the array of data that's constant, not the pointer itself). Could I makeauto
deduce tochar const* const
or can I change the code to make it result in such a type?