According to the C++ standard a string literal type is array of const char
auto constStr = "aaa";
char* nonConstStr = constStr; //Error here, cannot convert from 'const char *' to 'char *'
char* stillNonConstStr = "aaa"; //Why I don't have error here?
Can you please explain me why on the 3rd line I don't get an error?
Historical reasons. It used to be allowed, and very common, to assign from a string literal to a char*
, even though the type of a string literal is an array of const char. I believe it comes from days in C
where const
didn't exist, but don't quote me on that. It was later deprecated, but still allowed so as not to break codebases that used it. That allowance does not extend to allow char*
to be initialized from const char*
(nor from arrays of const char that are not literals), which is why your second line fails. In C++11, the conversion from string literal to char*
is banned, but your compiler may not enforce that yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With