• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1442
  • Last Modified:

String literal converted to char* in formal argument

Hi
I have a small snipet of code that compiles fine in VC++ 6.0 but throws the warning
String literal converted to char* in formal argument , while compiling with Solaris 5.6, CC compiler.
Even though the run time results are correct, I would like to remove this warning

Any suggestions.

#include<iostream>
using namespace std;
class A
{
public:
        void hi(string a){
        cout<<"String "<<a.c_str()<<endl;
        }
        void hi(char* a){
        cout<<"char* "<<a<<endl;
        }
};
int main(int argc, char *argv[])
{
        string a="HAHHAHAHAHH";
        A b;
        b.hi(a);
        b.hi("HOHOHOHOHO");

        return 1;
}


Thanks
Lohit
0
lohitverma
Asked:
lohitverma
1 Solution
 
SalteCommented:
Just change the type of A::hi() argument to const char * and the warning should go away.

A::hi(char * a) should change to A::hi(const char * a).

#include<iostream>
using namespace std;
class A
{
public:
       void hi(string a){
       cout<<"String "<<a.c_str()<<endl;
       }
       void hi(char* a){ // change here to const char * a.
       cout<<"char* "<<a<<endl;
       }
};

The reason for the warning is that char * means that you are able to modify the argument. A string literal should probably not be modified and so you can't use it as argument to a function that takes 'char *' as argument.

const char * a as argument means "I promise not to modify this string" and such an argument can receive a string literal without problems.

Since your function actually doesn't modify the string there's no reason why it should be 'char *'.

If a data type is 'char *' it will automatically convert to 'const char *' when necessary. The opposite is not true however, so a 'const char *' string can not change to 'char *' unless you use const_cast<> but that should not be necessary in your case.

Alf
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now