Richard Heathfield said:
santosh said:
Richard said:
Dead Loop said:
// more information
If I define p & p_const in a function as follows:
char *p = "Hello, world!";
const char *p_const = "Hello, world!";
It seems that a TI's compiler doesn't allow
p_const[0] = 'A';
but it allows
p[0] = 'A';
And MSVC6.0 doesn't allow both of them.
What about the C standard?
The C Standard says, in effect, "don't do that", but doesn't actually
prevent you from doing it. [...]
MSVC is within its rights to prevent modification of a string
literal, [...]
Can MSVC be a conforming compiler by preventing modification of string
literals?
Sure. If you try to do it, the behaviour is undefined, so all bets are off.
Implementations can do what they like, and that certainly includes
preventing the modification.
On the other hand, actually treating string literals as "const" is
potentially non-conforming. gcc, for example, does this with
"-Wwrite-strings", but that by itself doesn't make gcc non-conforming;
it merely causes it to issue some (misleading) warning messages.
For example, this program:
#include <stdio.h>
int main(void)
{
char *s = "hello, world";
puts(s);
return 0;
}
is strictly conforming (modulo any questions about the success or
failure of writing to stdout). But if string literals really were
const, then assigning the address of one to a non-const char* would be
a constraint violation. gcc with "-Wwrite-strings" warns:
c.c:4: warning: initialization discards qualifiers from pointer target type
But the program still compiles and executes, and an implementation can
issue any extraneous diagnostics it likes.
With "-Wwrite-strings -Werror", gcc rejects this program, and is
therefore non-conforming.
Assigning the address of a string literal to a non-const char* creates
the *potential* for attempting to modify the literal. A conforming
compiler is not allowed to reject the program based on that potential.
But if the program actually attempted to modify the string literal:
char *s = "hello, world";
s[0] = 'h';
that would invoke undefined behavior, and one valid consequence of
that is rejecting the program during compilation.
Enclosing the assignment in "if (0) { ... }" raises some interesting
questions, but I've already strayed enough from what the OP was
actually asking.
Hmm. I wonder if MSVC6.0 was being invoked as a C++ compiler. I
think C++ has different rules about string literals than C does.