String literals, represented by a text surrounded by double quotes like "Hello world"
are stored in read-only memory and cannot be
mutated.
Historically, string literals were introduced in C before the keyword const
so it was possible to create a mutable pointer to a string
literal:
char * ptr = "Hello world!"; // Noncompliant
To maintain retro-compatibility with the enormous amount of code that had been written without const, pointing to a string literal with a mutable
char pointer remained allowed in C, and although it has been officially removed from C++ since C++11, most compilers still allow it with a
warning.
Because it is a pointer to read-only memory, trying to modify ptr
will lead to undefined behavior. And because it is not declared as
const
, the type system will not be able to prevent or warn of such modification attempts.
Exceptions
This rule doesn’t raise an issue for explicit conversions to char *
.
char * ptr = (char *)"Hello world!"; // Compliant by exception, but you should avoid it.
This can be necessary in some very specific cases where an external API takes a mutable char *
with the clear contract that it will
never modify it.
That remains a very dangerous pattern that should be avoided as much as possible.