Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can const char* const & = "hello" compile?

I am reading a code snippet from a book and find this:

const char* const & a = "hello"; //can compile  const char*& a = "hello"; //cannot 

All I know is that when initializing a reference, the array to pointer conversion would not take place.

const char* const &, a reference to a const pointer, the pointer points to const char.

const char*&, a reference to a pointer, the pointer points to const char.

So why does adding an extra const, indicating that the pointer is a const, allow it to compile?

like image 480
Rick Avatar asked Aug 27 '18 04:08

Rick


People also ask

What does const char * const mean?

const char* means pointer to constant character. char const* means exactly the same as 1. (you probably were going for char* const , which is constant pointer to a character.)

What is a const char * in C?

const char* is a mutable pointer to an immutable character/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so.

Can a char * be passed as const * argument?

In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...

How do the following operators differ 1 char const * p 2 char * const p?

NOTE: There is no difference between const char *p and char const *p as both are pointer to a const char and position of '*'(asterik) is also same. 2. char *const ptr : This is a constant pointer to non-constant character. You cannot change the pointer p, but can change the value pointed by ptr.


1 Answers

It's essentially adhering to this formula

T const & a = something_convertible_to_T; 

Where T is const char*. In the first case, a temporary pointer can be materialized, assigned the address of the literal, and then have itself bound to the reference. In the second case, since the lvalue reference isn't const, it can't happen. Another example of more of the same

const char* && a = "hello"; // rvalue ref makes a no into a yes. 

Now the temporary pointer is bound to an rvalue reference.

like image 89
StoryTeller - Unslander Monica Avatar answered Sep 27 '22 18:09

StoryTeller - Unslander Monica