Deprecated conversion from string literal to 'char*'

C++StringCharDeprecatedLiterals

C++ Problem Overview


I have a program which declares an array of strings like this:

char *colors[4] = {"red", "orange", "yellow", "blue"};

But I get the above compiler warning. It compiles but I'd rather use the non-deprecated way(if there is one). I've tried to find out what it means, but I can't seem to figure it out. I've heard using 'const' before 'char' works, but it would be helpful if someone could explain what the error means. Thanks.

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

"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.

Solution 3 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - C++d_inevitableView Answer on Stackoverflow
Solution 2 - C++BЈовићView Answer on Stackoverflow
Solution 3 - C++tiktakView Answer on Stackoverflow