The error message you are getting from MinGW/Windows compiler strongly suggests that you are compiling this code as C++. In C language string literals have char[N]
type (as opposed to const char[N]
in C++). In C language you should not get this error message. Nevertheless, even in C string literals are non-modifiable, meaning that it is a good idea to stick to const char *
pointers when pointing to string literals.
Your question number 1 is a bit weird. String literals are nameless objects, which means that initialization is the only way to directly make a pointer to point to a string literal. There's no other way. Later you can copy your non-const pointer to other non-const pointers, which is OK. Just remember that you are not allowed to write anything into a string literal through those pointers: string literals are non-modifiable.
Your question 2 also makes little sense. "Visibility" is a property of a name. String literals are nameless objects. They are not visible anywhere. They can't be visible, since they have no names. Since they have no names, the only way to "grab" a string literal and hold on to it is to attach a pointer to it during pointer initialization (as in your examples). Visibility has nothing to do with it at all. String literals do indeed have static storage duration, which means that they "live forever": they exist as long as the program runs. In your example, string literals "Hans"
and "Gretel"
continue to live even after the foo
exits, meaning that the pointer returned by foo
remains valid.
The answer to your question 3 is: implicit conversions from const pointers to their non-const counterparts never existed in C language, i.e. it has always been invalid. You have to use an explicit cast in order to perform such a conversion.