Search code examples
c++charconstants

Why is it not allowed to assign const char * to const variable?


char* name;
const char* _name = "something";
name = _name; // conversion from const char * is not allowed

I know it is deprecated in c++, but I want to know why...

Why C++ banned name to point some literals _name points to?


Solution

  • Because name is non-const, it implies you are allowed to change the values.

    For example:

    *name = 'S'; // Change from "something" to "Something"
    

    But _name was declared const, meaning you cannot change it.

    You cannot take fixed, constant data, and assign it to a different variable; that is saying "It's OK if you change this".