Thank you. I'll do that.
But, I still don't get it.
Declaration and initialization like this:
char *var = "Some string";
Makes var pointing to a constant string; so, what's the point in making it a constant again by doing:
const char *const var = "Some string";?
In the good old days before C++, it would be quite permissible in C to write on your string:
var[4]='X';
C++ doesn't like that (although I think you can still do it) so it issues warnings. Using const formalizes your agreement that you won't do any such thing.
wildbill:
In the good old days before C++, it would be quite permissible in C to write on your string:
var[4]='X';
C++ doesn’t like that (although I think you can still do it) so it issues warnings. Using const formalizes your agreement that you won’t do any such thing.
String literals are not modifiable (and in fact may be placed in read-only memory such as .rodata). If a program attempts to modify the static array formed by a string literal, the behavior is undefined.
pagemaker:
so, what's the point in making it a constant again by doing:
const char *const var = "Some string";?
const char *const var = "Some string";
The red const is your promise to the compiler that you won't try to change the value of the string literal.
The blue const is your promise to the compiler that you won't try to change the pointer that points to the string literal (which would strand the literal in memory with no way of accessing it).
@gfvalvo
The red const is superfluous, because declaration/initialization makes the string by definition immutable.
The blue const makes sense, because we promise not to change the address of the pointer.
Anyway: char const *var = "some string" silences the warning.
Thanks all.
Changing 'char *' to 'const char *' does NOT 'make the data constant again'. The data is always constant, so you need a pointer that points to constant data.
The data type of a string constant is always 'const char *', so your variable that you assign to should be the same type.