13

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?

Mircea Ispas
  • 20,260
  • 32
  • 123
  • 211

2 Answers2

14

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.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
12

In C++03, there was a special rule ([conv.array]§2) which allowed string literals to be converted to type char*.

In C++11, this rule no longer exists. In other words, your code is valid C++03, but invalid C++11.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • *illformed* or *deprecated* C++11. Not invalid. This would still compile for historical reasons. [See here without -Wall](http://ideone.com/Itv8Hz) or [here with -Wall -Werror](http://coliru.stacked-crooked.com/view?id=bf8d5e2bc40d1220813841a85bfdbe25-18aa934a8d82d638dde2147aa94cac94) – Rapptz Mar 12 '13 at 07:24
  • 7
    @Rapptz: illformed == invalid. – Benjamin Lindley Mar 12 '13 at 07:26
  • 2
    @Rapptz Beware, *illformed* != *deprecated*, *"deprecated"* things work but are discouraged, *"illformed"* (and *"invalid"*, as *Benjamin* says) things *don't* work. – Christian Rau Mar 12 '13 at 08:09