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?
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.
String literals are, indeed, constant. However, arrays decay to pointers, and you took the non-const
pointer to the first element in the array:
char *str2 = "this is good";
Modifying any value of the const char array yields undefined behavior.
This will not compile clean under gcc 4.7.2. If you turn the warning levels up to Warning Level 4 under MSVC, it likely will emit a warning there, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With