I have a program which declares an array of strings like this:
char *colors[4] = {\"red\", \"orange\", \"yellow\", \"blue\"};
But I get the
These answers are all correct.
Note that if you have a function requiring an array of characters as an argument and you pass this argument like this:
foo ("bar");
the same warning will be shown. In this case, you can either :
1) Change it like this, as explained in the first answer:
void foo (char[] str) { printf(str); }
const char param[] = "bar";
foo (param);
2) Consider using a C++ standard string, like so:
void foo (std::string theParam) { std::cout << theParam; }
foo ("bar");
IMHO, as long as no real performance issue is concerned and you are not working with C libraries, or if you are building a C++ library for others to use, you should rather work with C++ immutable strings and their feature set.
If Unicode is a requirement, the support in C++ is "terrible" as explained here.
This question gives you some clues (mainly: use IBM ICU library). If you already have Qt in your project, QString
will also do the trick, and so will Gettext.
The strings that you enter: "red", "organge" etc are "literal", because they are defined inside the program code itself (they are not read directly from disk, user input /stdin etc.).
This means that if at any point you try to write to your colors
you will be directly accessing your original input and thus editing it. This would cause some undesired run-time errors.
Declaring it as a const will make sure that you will never try to write to this pointer and such a run-time error can be avoided.
const char *colors[4] = {"red", "orange", "yellow", "blue"};
If you ever feel like editing these values at runtime, then you should copy the strings first.
"red", "orange", "yellow", "blue"
these are constant string. Creating a non-const pointer to a constant string is wrong, hence the warning. At the moment you are getting a warning, but it should be an error since it is deprecated in c++03, and forbiden in c++11.