Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings] [duplicate]

Tags:

c++

warnings

very simple code does warn me. Some hints are not constructive. Warning is:

ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

I tried:

char const *q = "pin";
char const *r = "\n\r";
{
while(client.findUntil(*q, *r)) 

without success

Origin code:

while(client.findUntil("pin", "\n\r"))
like image 802
realhanno Avatar asked Jun 10 '19 10:06

realhanno


1 Answers

ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

while(client.findUntil("pin", "\n\r"))

The warning means that your program is ill-formed. You didn't show the declaration, but from context, we can deduce that the argument of findUntil is char*. You may not pass a string literal to such function.

It used to be well-formed - but deprecated - to pass a string literal as char* prior to C++11.

I tried:

char const *q = "pin";
char const *r = "\n\r";

These are correct by themselves, but

while(client.findUntil(*q, *r)) 

This makes no sense. Previously your were attempting to pass a string, but now you indirect through the character pointer so you are passing a character. Unless the function is a template, this cannot possibly work.

findUntil(q, r) won't work either, because the pointers to const won't implicitly convert to pointers to non-const.

A correct solution is to copy the string literals into modifiable arrays:

char q[] = "pin";
char r[] = "\n\r";
{
    while(client.findUntil(q, r)) 

Another is to fix findUntil to accept a pointer to const char instead. Then you can use string literals, since they can be converted to a pointer to const char.

like image 106
eerorika Avatar answered Oct 28 '22 07:10

eerorika