user2131316
user2131316

Reputation: 3277

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

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++?

Upvotes: 6

Views: 9126

Answers (4)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

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).

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

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.

Upvotes: 17

Taimour
Taimour

Reputation: 129

In c++ you can write it like this, void getAge(string name) { // do something } and also include the header file #include<string> because you are using string now

Upvotes: 0

ChronoTrigger
ChronoTrigger

Reputation: 8617

You can try getAge((char*)"hello").

Upvotes: 0

Related Questions