Mark said:
You're rigth, sadly. What an awful choice. I still find bugs like this
where people assume a char * is writable (as one might expect) but where
the pointer points to a string literal. Wouldn't it have been better to
have string literals be of type const char *?
According to the Rationale, string literals have this
peculiar property to avoid breaking existing code:
[...] string literals do not have the type /array
of const char/ in order to avoid the problems of
pointer type checking, particularly with library
functions, since assigning a /pointer to const char/
to a plain /pointer to char/ is not valid. [...]
As an example of how `const' literals could break
perfectly good existing code, consider this pre-C89 program:
#include <stdio.h>
greet(whom)
char *whom;
{
printf ("Hello, %s!\n", whom);
}
int main() {
greet ("world");
return 0;
}
Note that greet() takes a plain `char*' argument, because
a pre-C89 coder had no way to write a `const' qualifier: the
keyword was added to the language (along with `void' and some
other "new stuff") by the ANSI committee. Now, what would
have happened if the committee had made string literals be
`const char[]'? The call to greet() in main() would have
become illegal, because you can't convert `const char*' to
plain `char*' without a cast.
Now multiply this trivial example by the twenty or so
years' worth of C code in existence before the new Standard
came along. If every string-accepting function in the entire
corpus of existing code had suddenly started refusing to accept
string literals as arguments, the new Standard might have had
some slight difficulty in gaining acceptance ...
Hindsight often tells us how things ought to have been
done differently, but it's not always possible to undo them.
The Clacking Keyboard writes: and having writ,
Clacks on: nor all thy Prototypes nor Wit
Shall rewind() it to fgets() half a Line,
Nor all thy Tears re-Const a Char of it.