ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings]

I got a warning as you can read from the title.
Precisely this is this line that is affected :

1
2
 Rectangle(double, double,
               char *);


After some research I got to know that to fix it I should do the following :

1
2
 Rectangle(double, double,
              const char *); // I add the "const" 


Can you give me your own explanation of the warning? I fixed the issue without really understanding that's why.

The problem is not in the lines that you're showing, the problem is how you're calling the function. It appears that you're calling the function with a "string literal" (a constant char*), ie Rectangle(1.0, 2.9, "THIS IS THE VALUE YOU'RE PASSING").
Why I shouldn't do it? and why const char * fix it then?
Last edited on

and why const char * fix it then?

When you add the "const" you are informing the compiler that the function will not try to modify the variable. Remember that you can never modify a "string literal". That pointer can be and usually is pointing to the "Code" segment, which is not writable, hence the need for a const char *.

Why I shouldn't do it?


Do what, exactly? In this instance the compiler won't let you pass a "string literal" via a non-const char pointer, hence the error message.

you can ugly it up and do it with S.

1
2
3
4
5
6
7
8
void foo(const char * cp)
{
  cout << cp << endl;	
}
int main()
{
	foo(("text"s).c_str());


if you are not allowed to use this, you have to clunk:
copy the constant into a variable, and pass the variable to the function, or better, get rid of the constant:
char passme[] = "constant text";
foo(passme); //ok
Last edited on
Topic archived. No new replies allowed.