user2269250
user2269250

Reputation: 11

can't convert from char * to const char *&

I have a funciton like

    void foo(const char *&str)
    {
         cout<<str<<endl;
    }

used like:

    void main()
    {
        foo("hello");
        char *h = "hello"
        foo(h);
    }

but both got an error

"can't convert from const char[] to const char *&"

if I change foo to void foo(const char *), there is no error can't I use const char *& as parameter

Upvotes: 1

Views: 5608

Answers (2)

john
john

Reputation: 87959

This will work

int main()
{
    const char *h = "hello";
    foo(h);
}

Upvotes: 1

James Kanze
James Kanze

Reputation: 153899

You got an error because the conversion is illegal. The reason it is illegal is simple: it breaks const without requiring a const_cast.

As an example of why it is forbidden, imagine that foo was:

void
foo( char const*& str )
{
    str = "abc";
}

int
main()
{
    char* h;
    foo( h );
    *h = '1';
}

If you're not going to modify str in foo, pass by value. Pass by reference will works if you have char const* const&, but there's no reason to use it here. It works because the additional const means that you can bind a temporary to it (as in the case of foo( "hello" ), where the argument is a temporary resulting from the conversion of char const[6] to char const*, and foo( h ) works, because the implicit const conversions will work (in C++, but not in C!), as long as you add const everywhere (and not just at one level).

Also, your code also uses a deprecated conversion to initialize h. You should get a warning here. And void main is an error, and shouldn't compile.

Edit:

Just to be clear, there's no problem with:

void f( char const*& str );

But you can only call it with an lvalue of type char const*; anything else will either result in an illegal implicit const conversion, or try to initialize a non-const reference with an rvalue, which is illegal.

Upvotes: 2

Related Questions