Search code examples
c++c-stringsstring-literals

Why do I get a compiler warning for converting a string literal to a char*, is it bad?


So the compiler tells me this is a deprecated conversion from a string-literal to char*:

 char* myString = "i like declaring strings like this";

Should I be worried about this? Is this the wrong way to do this?

I need to pass myString to a function that accepts a char* , who should I properly initialize the char* without this conversion?


Solution

  • It shouldn't even compile. If you need to pass it to function that you are sure won't change the string you need to use const cast, its one of its correct uses:

    functionName(const_cast<char *>("something"));
    

    Or if you don't want the const cast, you can copy the string to the stack:

    char str[] = "something";
    functionName(str);