String declaration works when I declare in the the following ways:
string a = "xyz";
char a[] = "xyz";
But in case of:
char *a = "xyz";
It gives an ERROR in g++ 4.9.2 compiler:
warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] char *a = "xyz";
I think these three declaration types are different from each other. Please help me out.
In earlier version(s) of the language, you could use:
Now, you must use:
A string literal, such as
"xyz"
resides in the rea-only parts of the program. It can be used to initialize achar const*
since you are not supposed to modify the contents of what achar const*
points to. Using it to initialize achar*
opens the possibility of a user modifying them accidentally. In addition, modifying such strings is cause for undefined behavior.A string literal can also be used to initialize a
char[]
. In that case, the string literal is copied to the space allocated for the array. Hence, there is no risk of modifying read-only data of the program. Hence, usingis OK.
The line
invokes the constructor of
string
that takes achar const*
and then uses that object to initializea
. Hence, that line is also OK.This uses initializer syntax to invoke the constructor
std::string( const char* )
.This declares an array large enough to store the string plus terminator. It follows standard array-initializer rules. Think of it as equivalent to
char a[] = { 'x', 'y', 'z', '\0' };
This takes a string literal (
"xyz"
) and assigns it to a non-constant pointer. Within the language, such a pointer means it is okay to modify the string it points to, but that is undefined behaviour in this case, because string literals may not be modified. To prevent you from making such a mistake, the compiler gives you a warning. The following is valid and will not emit a warning: