In C, character string literals are stored in arrays of type char
The type of a narrow string literal is array of char
and the type of a wide string literal is array of wchar_t
. However, string literals (of both types) are notionally constant and should consequently be protected by const
qualification. This recommendation is a specialization of DCL00-A. Const-qualify immutable objects and also supports rule STR30-C. Do not attempt to modify string literals.
Adding const
qualification may propagate through a program; as you add const
qualifiers, still more become necessary. This phenomenon is sometimes called "const-poisoning." Const-poisoning can frequently lead to violations of EXP05-A. Do not cast away a const qualification. While const
qualification is a good idea, the costs may outweigh the value in the remediation of existing code.
Non-Compliant Code Example (narrow string literal)
In the following non-compliant code, the const
keyword has been omitted.
...
Wiki Markup |
---|
Consequently, a statement such as {{c\[0\] = 'C'}} is valid and behaves as expected. |
Non-Compliant Code Example (wide string literal)
In the following non-compliant code, the const
keyword has been omitted.
Code Block |
---|
|
wchar_t *c = L"Hello";
|
Wiki Markup |
---|
If a statement such as {{c\[0\] = L'C'}} were placed following the above declaration, the code is likely to compile cleanly, but the result of the assignment is undefined as string literals are considered constant. |
Compliant Solution (immutable strings)
In this compliant solution, the characters referred to by the pointer c
are const
-qualified, meaning that any attempts to assign them to different values is an error.
Code Block |
---|
|
const wchar_t *c = L"Hello";
|
Compliant Solution (mutable strings)
In cases where the string is meant to be modified, use initialization instead of assignment. In this compliant solution, c
is a modifiable char
array which has been initialized using the contents of the corresponding string literal.
Code Block |
---|
|
wchar_t c[] = L"Hello";
|
Wiki Markup |
---|
Consequently, a statement such as {{c\[0\] = L'C'}} is valid and behaves as expected. |
...