Why do compilers allow string literals not to be const?
Solution 1:
The C standard does not forbid the modification of string literals. It just says that the behaviour is undefined if the attempt is made. According to the C99 rationale, there were people in the committee who wanted string literals to be modifiable, so the standard does not explicitly forbid it.
Note that the situation is different in C++. In C++, string literals are arrays of const char. However, C++ allows conversions from const char * to char *. That feature has been deprecated, though.
Solution 2:
Mostly historical reasons. But keep in mind that they are somewhat justified: String literals don't have type char *
, but char [N]
where N
denotes the size of the buffer (otherwise, sizeof
wouldn't work as expected on string literals) and can be used to initialize non-const
arrays. You can only assign them to const
pointers because of the implicit conversions of arrays to pointers and non-const
to const
.
It would be more consistent if string literals exhibited the same behaviour as compound literals, but as these are a C99 construct and backwards-compatibility had to be maintained, this wasn't an option, so string literals stay an exceptional case.