I am wondering about the compiler's decision to let the statement: str1[2]='x'; get by without error. Would it be fair to say that:
char *str1 = "abcd";
const char *str1 = "abcd";
are identical statements, since the string literal is a constant. In which case wouldn't it be adviseable for the compiler to generate a diagnostic for the assignment to str1 as it does for str2 ?
Or could there be a situation where it is possible, and legal, to change the string literal contents and therefore the const'ness of *str1 cannot be assumed?
All string literals are const char *, and modifying them is always illegal.
Line 7 has an implicit cast to char * which some compilers (such as VC++) allow. g++ gives a warning (something along the lines of "deprecated cast to 'char *'").
The type of a string literal is "array of the appropriate number of const characters".
[In other words, "string" is of type 'const char[7]'.]
[...]
A string literal can be assigned to a char *. This is allowed because in previous definitions of C and C++ , the type of a string literal was char *. Allowing the assignment of a string literal to a char * ensures that millions of lines of C and C++ remain valid. It is, however, an error to try to modify a string literal through such a pointer[.]
Thanks Hammurabi, and esp. thanks helios for the quote from Stroustrup. That pretty much nails it on the head. I don't think I'm quite ready to argue about C++ standards with Mr. Stroustrup, I'll wait 'till I have a few more months C++ under my belt before I do that.