Milad Khajavi
Milad Khajavi

Reputation: 2859

How to hardcode c-string in `non-const reference of type char* &` argument

Why can't I compile this program?

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


 foo( "foo" ); //Compiler Error!! Why?

 const char* str = "foo";
 foo( str ); // No Erro

How can I hardcode my argument? like foo ( "MyString" ) ?

Upvotes: 0

Views: 3376

Answers (4)

Drew Dormann
Drew Dormann

Reputation: 63912

A const char* & is a reference to some pointer that exists somewhere.

Here, there is no such pointer to refer to. There is a character array, but creating an array does not create a pointer.

foo( "foo" ); //Compiler Error!! Why?

Here, there are both an array "foo" and a pointer to that array.

const char* str = "foo";
foo( str ); // No Erro

Edit from comment:

So why I can't write foo( &"foo" ) ?? address of "foo" array?

Try thinking of it this way.

It's the same reason you can't write &&&&&&"foo" to create a char*******.

A char******* would be a pointer to memory where there's a pointer to memory where there's a pointer... (You get the idea)

C++ will not automatically create all these things in memory for you.

Upvotes: 1

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234654

"foo" has type char const[4], not char const*. An array cannot bind to a reference to a pointer, because arrays are not pointers.

Upvotes: 1

Pubby
Pubby

Reputation: 53067

Literals can't bind to non-const lvalue references.

Same reason you can't do this:

void foo(int& x) {}
// ..
foo(5);

You can use an rvalue reference though:

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

I don't recommend this though.

Anyway, it's pointless to modify the pointer as it's a temporary and will immediately go out of scope anyways. Why are you doing this? Do you really intend const char* const& which will bind to both?

Upvotes: 1

75inchpianist
75inchpianist

Reputation: 4102

"foo" is not of type const char*

the second declaration is.

Upvotes: 0

Related Questions