You are not allowed to modify the memory you get from a string literal, so for that reason it is more correct to use const char*. Modern compilers often warn you if you don't.
constchar* c = "XYZ";
This will give you a compilation error instead of a runtime error if you accidentally try to modify the string.
Are you trying to say that once I declare:
char* c="XYZ";
I cannot modify c?
I may have assigned a string literal, but since it is not declared to be constant, I should be able to change value but I can't. Why? :(
So if I want to change the value of the string literal, is the only way to copy it into another char* (that is perhaps dynamically allocated depending on situation) along with the changes?
> Are you trying to say that once I declare:
> char* c="XYZ";
> I cannot modify c?
No. I am saying that you cannot declare char* c="XYZ"; in a C++ program.
It will be diagnosed as an error by a conforming C++ compiler.
1 2 3 4 5 6
int main()
{
char* c = "XYZ" ;
// clang++: error: ISO C++11 does not allow conversion from string literal to 'char *'
// g++: error: ISO C++ forbids converting a string constant to 'char*'
}
Microsoft Specific
In Visual C++ you can use a string literal to initialize a pointer to non-const char or wchar_t. This is allowed in C99 code, but is deprecated in C++98 and removed in C++11. https://msdn.microsoft.com/en-us/library/69ze775t(v=vs.140).aspx