55

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"))
realhanno
  • 577
  • 1
  • 4
  • 3
  • 2
    The problem is likely `findUntil` not being declared const correct. Can't know for sure. – StoryTeller - Unslander Monica Jun 10 '19 at 10:32
  • The codes can’t be proper since one gets a literal string and the other a `char` due to dereferencing, so it cannot complain about `char*` – Sami Kuhmonen Jun 10 '19 at 10:36
  • 1
    I was getting this same warning on arduino with char* allNames[5] = {"one","two"...}. Thanks to comment I altered to const char* allNames[5] = {"one",...} and the warning went away. Thanks. – raddevus May 30 '21 at 15:50
  • if you can change client method the change it to findUntil(const char* p, const char* q) – R_K Feb 08 '22 at 17:10

1 Answers1

39

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.

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 19
    I solved it with following code: `char* q = (char*)"pin";` `char* r = (char*)"\n\r";` `... while(client.findUntil(q,r); ...` – realhanno Jun 10 '19 at 10:46
  • 4
    @realhanno that's slightly dangerous unless you know exactly what the function `findUntil` does, and in particular know that it doesn't modify the strings pointed by the arguments. Fixing `findUntil` to use pointers to const char is better solution. – eerorika Jun 10 '19 at 10:48
  • Thanks. Function is good. And better... – realhanno Jun 10 '19 at 10:56