Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't you have a non-const char* in C++?

Why does this work:

char foo[6] = "shock";`

while this does not work:

char* bar = "shock"; //error

Why does bar have to be const while foo doesn’t? Arrays in C decay to pointers, so don’t foo and bar technically have the same types?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With this declaration:

char foo[6] = "shock";

Variable foo is type array of char and it containes 6 non-const chars. The string literal contains const chars which are copied into the array on initialization.

While with this declaration:

char* bar = "shock"; //error

Variable bar is type pointer to char. You are trying to make it point to the address of "shock" which is a string literal containing const char.

You can’t point a pointer to non-const char at a const char.

So you must do this:

const char* bar = "shock";`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading