C does not allow programs to modify a string literal.
However, for historic reasons this is not reflected in their type.
E.g. this compiled, but has undefined behaviour if ever executed:
void f(void)
{
"test"[2] = 'a';
}
It would be more consistent is the element type for string literals
would be const-qualified. And coding standards (e.g. MISRA) require the
use of const-qualified types already in e.g.
const char *c = "test"; // OK
vs.
char *c = "test"; // Allowed by C standard, not allowed by MISRA
I don't think this change would break many recent programs. So even if
the type of char string literals cannot be changed, such a change should
at least be possible for string literals of other types.
Is it worth writing a proposal for C2X?
What do you think of such a change?
Philipp
The best alternative is to have it as a compiler switch. gcc's "-fwrite-strings" option does exactly this, and I use it in my own code.
(I disagree with the naming - as it affects the semantics of the
language, it should not be a "warning" option - but that's another matter.)
* David Brown:
The best alternative is to have it as a compiler switch. gcc's
"-fwrite-strings" option does exactly this, and I use it in my own code.
(I disagree with the naming - as it affects the semantics of the
language, it should not be a "warning" option - but that's another matter.)
The historic -fwritable-strings option actually made string literals
writable by placing them into the data segment.
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 365 |
Nodes: | 16 (2 / 14) |
Uptime: | 32:33:55 |
Calls: | 7,769 |
Files: | 12,905 |
Messages: | 5,749,362 |