C99 6.4.5/5 seems to say that string literals have type char[] .
However, the version of GCC I have installed fails to compile the following
code, giving the error
foo.c:6: error: assignment of read-only location
This happens with "-ansi" and with "-std=c99" , with or without the
other usual warning switches.
Is this a GCC bug or am I misinterpreting the standard?
Not a bug, because a compiler is always allowed to issue
any diagnostics it likes. That's why gcc can issue a warning
for `if (x = 0) ...' even though it's perfectly legal C.
#include <stdio.h>
int main(void)
{
if ( 0 )
"abc"[0] = 1;
If the assignment were attempted, the behavior would be
undefined. The anonymous array created by the string literal
is of type `char[4]' rather than `const char[4]', but that's
a historical accident: `const' was a latecomer to C. Despite
the array's non-`const'-ness, attempting to modify it yields
undefined behavior.
Perhaps one could argue that the compiler should have seen
that the assignment would never be executed, optimized the whole
business away, and suppressed the warning -- but that's an argument
to have with the compiler developers, not with the language.
More on the "historical accident:" Before `const' there was no
way for a function to advertise that it didn't intend to write through
a pointer argument. A function operating on a string looked like:
int oldfunc(string)
char *string;
{ ... }
It looked this way whether it wanted read-only or read-write access;
the function definition was the same either way. Along came `const'
and it became possible to state the difference:
int readwrite(string)
char *string;
{ ... }
int readonly(string)
const char *string;
{ ... }
or with prototypes (which came along at the same time):
int readwrite(char *string) { ... }
int readonly(const char *string) { ... }
At this point the Committee *could* have `const'-ified the string
literal's array, but then what would have happened to oldfunc() --
to all those oldfunc()'s in their myriad thousands in C code that
had been written in the two decades preceding the ANSI Standard?
Every attempt to call them with literal arguments would suddenly
become an "error by fiat" -- with a diagnostic required, no less.
How eager would folks have been to adopt a brand-new Standard whose
immediate effect was to delegitimize a huge amount of pre-existing
code? So the Committee took the "impure" but intensely practical
stance that the literal arrays would be "non-`const' but please
don't write them." That's the situation that still prevails.