C compilers are not required to detect the first error, because C string literals are not const
.
Referring to the N1256 draft of the C99 standard:
6.4.5 paragraph 5:
In translation phase 7, a byte or code of value zero is appended to
each multibyte character sequence that results from a string literal
or literals. The multibyte character sequence is then used to
initialize an array of static storage duration and length just
sufficient to contain the sequence. For character string literals, the
array elements have type char, and are initialized with the
individual bytes of the multibyte character sequence; [...]
Paragraph 6:
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.
(C11 does not change this.)
So the string literal "hello, world"
is of type char[13]
(not const char[13]
), which is converted to char*
in most contexts.
Attempting to modify a const
object has undefined behavior, and most code that attempts to do so must be diagnosed by the compiler (you can get around that with a cast, for example). Attempting to modify a string literal also has undefined behavior, but not because it's const
(it isn't); it's because the standard specifically says the behavior is undefined.
For example, this program is strictly conforming:
#include <stdio.h>
void print_string(char *s) {
printf("%s
", s);
}
int main(void) {
print_string("Hello, world");
return 0;
}
If string literals were const
, then passing "Hello, world"
to a function that takes a (non-const
) char*
would require a diagnostic. The program is valid, but it would exhibit undefined behavior if print_string()
attempted to modify the string pointed to by s
.
The reason is historical. Pre-ANSI C didn't have the const
keyword, so there was no way to define a function that takes a char*
and promises not to modify what it points to. Making string literals const
in ANSI C (1989) would have broken existing code, and there hasn't been a good opportunity to make such a change in later editions of the standard.
gcc's -Wwrite-strings
does cause it to treat string literals as const
, but makes gcc a non-conforming compiler, since it fails to issue a diagnostic for this:
const char (*p)[6] = &"hello";
("hello"
is of type char[6]
, so &"hello"
is of type char (*)[6]
, which is incompatible with the declared type of p
. With -Wwrite-strings
, &"hello"
is treated as being of type const char (*)[6]
.) Presumably this is why neither -Wall
nor -Wextra
includes -Wwrite-strings
.
On the other hand, code that triggers a warning with -Wwrite-strings
should probably be fixed anyway. It's not a bad idea to write your C code so it compiles without diagnostics both with and without -Wwrite-strings
.
(Note that C++ string literals are const
, because when Bjarne Stroustrup was designing C++ he wasn't as concerned about strict compatibility for old C code.)