Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ const correctness with string literals [duplicate]

Tags:

c++

constants

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?

like image 768
Mircea Ispas Avatar asked Mar 12 '13 07:03

Mircea Ispas


1 Answers

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.

like image 187
Benjamin Lindley Avatar answered Nov 18 '22 00:11

Benjamin Lindley