Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid deprecated conversion from string constant to 'char*' in C++

Tags:

c++

arrays

c

char

I would like to call the following code in C++, which I cannot change:

void getAge(char *name)
{
// do something
}

When I call it with getAge("hello");, it has the following warning:

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

but there is no warning in C code. What is the difference, and how do I change the call to avoid the warning in C++?

like image 409
user2131316 Avatar asked Jun 18 '13 14:06

user2131316


2 Answers

the function […] can not be changed

Then write a wrapper around the function and copy the string – or, if you feel lucky (= you know that the string won’t be modified inside the original function), explicitly cast away const-ness:

void getAge(char const* name) {
    the_namespace::getAge(const_cast<char*>(name));
}

If you’re unsure whether the function modifies its parameters, use something like the following – however, if that’s the case then calling the function with a string literal (getAge("hello")) would have been invalid anyway.

void getAge(char const* name) {
    std::string buffer(name);
    the_namespace::getAge(&buffer[0]);
}

Here we copy the string into a modifiable buffer and pass an address to its first character to the original function.

like image 176
Konrad Rudolph Avatar answered Oct 21 '22 00:10

Konrad Rudolph


The safest way is to copy the string, then call the C function:

void getAgeSafe(const char* name)
{
  std::vector<char> tmp = name?
    std::vector<char>(name, name+1+strlen(name))
    :std::vector<char>();

  getAge( tmp.data() );
}

and call getAgeSafe from your C++ code.

A less safe way that relies on the C code never modifying the char* name would be to const_cast, again in a "wrapping" function:

void getAgeUnsafe(const char* name)
{
  getAge( const_cast<char*>(name) );
}

but this time the name is more scary, as is the operation. If you call getAge with a compile time constant string like "bob", if getAge modifies its input, undefined behavior results (this is true in both C and C++ -- C++ at least warns you about it).

like image 2
Yakk - Adam Nevraumont Avatar answered Oct 21 '22 00:10

Yakk - Adam Nevraumont