Related to Is it bad to declare a C-style string without const? If so, why? , but that question is about best practise, while mine is more language lawyer. Similar questions have been asked, but for C++ and not C.
I was under impression that code like char* s = "test";
is no longer legal C since the introduction of const
keyword in C, which made the literals have type const char*
instead of char*
. The compiler warnings usually use wording of "deprecated", which implies to me that they only allow it to compile old code.
However, reading https://en.cppreference.com/w/c/language/string_literal.html , const
is neither used in any examples, not even mentioned at all on the page. It only says:
String literals are not modifiable [...]. If a program attempts to modify the static array formed by a string literal, the behavior is undefined.
without recommending the obvious const
which would make it a compilation error.
Is cppreference incorrect (or incomplete) in this case, or does this deprecation work differently from what I expect?
n3550 seems the latest draft.
6.4.6 String literals
<...> For ordinary string literals, the array elements have type char
, and are initialized with the individual bytes of the multibyte character sequence corresponding to the literal encoding (6.2.9). <...>
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
Note, array elements are not const char
. So, char* s = "test";
is still valid and legal in C and compilers may not reject this code.