C++ warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

String literals are an array of const char, we can see this from the draft C++ standard section 2.14.5 String literals which says (emphasis mine):

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

so this change will remove the warning:

const char * commandsForGnuplot[] = {"set title \"Probability Graph\"", "plot     'data.temp' with lines"};
^^^^^

Note, allowing a *non-const char** to point to const data is a bad idea since modifying a const or a string literal is undefined behavior. We can see this by going to section 7.1.6.1 The cv-qualifiers which says:

Except that any class member declared mutable (7.1.1) can be modified,
any attempt to modify a const object during its lifetime (3.8) results
in undefined behavior.

and section 2.14.5 String literals which says:

Whether all string literals are distinct (that is, are stored in
nonoverlapping objects) is implementation defined. The effect of
attempting to modify a string literal is undefined.

Leave a Comment