Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to supply a 'const char*' argument for a function that takes a 'char*' in C++?

I have the following code.

const char* my_input = "my string";

void my_function(char* my_argument);

int main()
{
  my_function(my_input);
}

void my_function(char* my_argument)
{
  /* Do something */
}

Notice that the argument for my_function expects a 'char*', but I supply it with a 'const char*'.

My IDE gives me the error: No matching function for call 'my_function'.

I assume it is because the function call is being interpreted as 'my_function(const char* my_argument)', which I have clearly not defined (and do not want to).

How do I can I make it so that my constant input is valid for an expected non-constant argument?

In my real program, I have a function that takes in a 'char*', however it does NOT modify it. The argument itself might not be a constant (and isn't usually), however sometimes I expect a constant.

like image 355
Fine Man Avatar asked Oct 23 '25 04:10

Fine Man


1 Answers

It is not being interpreted as my_function(const char *) call. It is being interpreted as my_function(char *) call, since there's no other versions of my_function available anywhere. However, this is not allowed because it violates the rules of const-correctness of C++ language. These rules prohibit implicit conversion of const char * pointer to char * type.

The first question you have to answer here is why you are trying to pass a pointer to constant data to a function that potentially treats it as non-constant (modifiable) data. This is an obvious violation of const-correctness.

If your my_function does not really modify the data, then the next question is why it is declared with char * parameter instead of const char * parameter.

And only as the last resort, if you are sure that my_function does not really modify the data, but for some reason cannot change its declaration (e.g. third party code), you can work around this problem by forcing the conversion to char * type

my_function(const_cast<char *>(my_input));
like image 109
AnT Avatar answered Oct 25 '25 18:10

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!