Search code examples
c++xcodeclangstring-literalsgcc-warning

When a function is possible to be given a char* or literal string, what is the right way to declare this function?


This question is not a duplicate of question:deprecated-conversion-from-string-literal-to-char

But yes I'm trying to get rid of this annoying Clang warning. In that Answer there are the following ways:

  1. const_cast or (char*)
  2. foo(char*) -> foo(const char*)

I also found some solution in warning-deprecated-conversion-from-string-constant-to-'char'

  1. strcpy
  2. -Wno-write-string

My further question is :

  1. How to set -Wno-write-string in Xcode? Or is there actually such a flag in Clang just as in gcc/g++? I didn't find it in Clang Flag Ref

  2. In my code, I get functions that are defined as foo(char*), they receive string or char* for some time, and receive literal string(e.g. "hello") for other time. For such kind of case, what is the right or proper way to decl/def foo?


Solution

  • You can just make your input parameter of your function a const char* and it will work. A function that has its input parameter as const char* means that the function will not make changes to what the pointer points to! So this means it will work with both string literlas (which are const char* themselves) and with regular char* parameters.

    void printString(const char* str)
    {
        printf("%s", str);
    }
    

    This function can be called like this:

    int main()
    {
        const char* pointerToLiteral = "string";
        char* str = new char[16];
        std::strcpy(str, pointerToLiteral );
    
        printString("true literal");
        printString(pointerToLiteral );
        printString(str);
    
        delete [] str;
    }
    

    When you pass a pointer to printString function it makes a copy of that pointer on its stack. And that copy is now of type const char*. Which means that the code of printString cannot change what the pointer points to. There is no reason this would not work if you pass a pointer of type char* to it.

    Note that the other way around does not work. If we had printString(char* str), you cannot pass it a const char* parameter, because now the function is saying that it can make changes to what the pointer points too, but the const char* parameter does not allow that!