why can I assign a string literals to a char* pointer

c++, visual-c++

Solution

The question is under VC++, but in GCC it has a meaningful warning:

warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

This warning implies that compiler will apply an implicit conversion despite const/non-const differences. So, this code is OK (without any modification in run-time):

char *str2 = "this is good";

However modifying `str2` yields an undefined behavior.

Problem

I think the string literals in `c++` is the type of `const char*`. And you can't assign `const char*` object to a `non-constant char*` object. But in Visual studio 2010. The following code can compile without errors or warnings, which will however yield a runtime error. ``` int main(void) { char *str2 = "this is good"; str2[0] = 'T'; cout << str2; getchar(); return 0; } ``` And if we don't modify the value of the string, reading the value is ok: ``` for(char *cp = str2; *cp !=0; ++cp) { printf("char is %c\n", *cp); } getch(); return 0; ``` So why can we assign a const char* to a char* here?

Original source

Related problems