Friday, July 15, 2011

Fixing a warning: deprecated conversion from string constant to 'char*'

When using C++, you may get the warning "deprecated conversion from string constant to 'char*'" when compiling something similar to the following:

void foo(char *){}
...
foo("hi");

I have found three options to overcome this problem:

1. Add the 'const' keyword to the function definition:
void foo(const char *){}

2. Cast the string when calling the function:
foo((char *)"hi");

3. Create a char array to pass to the function:
char message[] = "hi";
foo(message);

Each might work better than the other 2 for a given situation. I leave it up to you to figure out which is best for your situation.

No comments:

Post a Comment