Avoiding stale 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 to change the call to avoid a warning in C ++?

+6
source share
4 answers

function [...] cannot be changed

Then write a wrapper around the function and copy the line - or, if you're lucky (= you know that the line will not be changed inside the original function), explicitly discard the constant:

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

If you are not sure that the function changes its parameters, use something like the following - however, if so, then calling the function with a string literal ( getAge("hello") ) would be invalid anyway.

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

Here we copy the string to the buffer to be modified and pass the address to the first character in the original function.

+17
source

The safest way is to copy the line, 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 secure way, which relies on C code that never changes the char* name , is const_cast , again in the "wrapping" function:

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

but this time the name is more terrible, like the operation. If you call getAge with a constant compile-time constant, for example, "bob" , if getAge changes its input, the results are undefined (this is true in both C and C ++ - C ++ at least warns you about this )

+2
source

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

0
source

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

0
source

Source: https://habr.com/ru/post/947558/


All Articles