Home > Back-end >  function(char message []) not compiling with function("Text");
function(char message []) not compiling with function("Text");

Time:03-18

I am having an issue with trying to send a char[ ] message from main to my function.

InputNum(char msg []) { cout << msg; }

then called as

int main() { InputNum num ("Enter a Number"); }

The above throws an error from the g compiler:

ISO C forbids converting a string constant to ‘char*’ [-Wwrite-strings]

So, I am sending a String in main as a char[ ]. But I'm not sure why that is a problem. I was under the illusion that a char[ ] IS a String, which I guess is incorrect. Any general advice on what and how to fix it, I would appreciate greatly.

Also, code is inspired by p.44 "C In Action" by Bartosz Milewski (2001).

CodePudding user response:

There are several problems with your given code.

Mistake 1

The type of the parameter msg in you function InputNum is actually a char* i.e., a pointer to char. This is because char[] decays to char* in case of pass by value. Meanwhile "Enter a Number" is a string literal of type const char[15] which decays to const char*. Thus, you're essentially passing a const char* as an argument where the parameter is of type char*. That is, there is mismatch in type of argument passed and the parameter msg.

To solve this you should add a low-level const to the parameter msg as shown below:

//-------vvvvv--------------->note the const added here
InputNum(const char msg []) 
{ 
    cout << msg; 
}

Mistake 2

You've not specified the return type of the function InputNum. To solve this you should add void as the return type as shown below:

//vvvv-------------------------------> note void added as return type here
  void InputNum(const char msg []) { 
      cout << msg; 
  }

Mistake 3

You should remove num from the statement InputNum num ("Enter a Number"); as shown below:

//------v------------------->num removed from here
InputNum ("Enter a Number");

Solution 1

Here is the complete modified solution incorporating all the above 2 solutions.

void InputNum(const char msg []) 
{ 
    std::cout << msg;
}
int main() 
{
    InputNum ("Enter a Number");
    
}

Demo

Solution 2

You can also use std::string as shown below:

void InputNum(const std::string& msg) 
{ 
    std::cout << msg;
}
int main() 
{
    InputNum ("Enter a Number");
}

Demo

CodePudding user response:

You are trying (unknowingly) to make a string literal writable. C doesnt like this at all.

You have to do

InputNum(const char msg []) {
   cout << msg;
}

this promises the compiler that you wont try to change the conents of 'msg'

  •  Tags:  
  • c
  • Related