String literals are constant and should only be assigned to constant pointers. This recommendation supports rule STR30-C.
Non-Compliant Code Example
...
The const
keyword is not included in this declaration.
Code Block | ||
---|---|---|
| ||
char *c = "Hello"; /* Bad: assigned to non-const */ c[3] = 'a'; /* Undefined (but compiles) */ |
Compliant Solution 1
The compiler will not allow In cases where the string referenced by c
is not meant to be modified, c
should be declared as a const
pointers,
preventing direct manipulation of the contents of the string literals that are assignhed to const
pointers.
Code Block | ||
---|---|---|
| ||
char const *c = "Hello"; /* Good */ //c[3] = 'a'; would cause a compile error |
Aside
Compliant Solution 1
In cases where the string referenced by c
is meant to be modified, use initialization instead of assignment. In this compliant solution, both a
and b
are modifiable char
arrays which have been initialized using the contents of the corresponding string literalNote that the following code is acceptable, as a
and b
do not actually point to string literals. They are char
array objects which have had characters copied into them, and therefore are modifiable.
Code Block |
---|
char a[] = "abc";
char b[3] = "abc";
|
The above code is equivalent to:
Code Block |
---|
char a[] = {'a', 'b', 'c', '\0'};
char b[] = {'a', 'b', 'c'};
|
Non-Compliant
...
Code Example
...
1
Though it is not compliant with the C Standard, this code executes correctly if the contents of CMUfullname
are not modified.
Code Block | ||
---|---|---|
| ||
char *CMUfullname = "Carnegie Mellon"; /* get school from user input and validate */ if (strcmp(school,"CMU")) { school = CMUfullname; } |
Non-Compliant
...
Code Example 2
...
Adding in the const
keyword will generate a compiler warning, as the assignment of CMUfullname
to school
discards the const
qualifier. Any modifications to the contents of school
after this assignment will lead to errors.
Code Block | ||
---|---|---|
| ||
char const *CMUfullname = "Carnegie Mellon"; /* get school from user input and validate */ if (strcmp(school,"CMU")) { school = CMUfullname; } |
Compliant Solution
...
The compliant solution uses the const
keyword to protect the string literal, as well as using strcpy()
to copy the value of CMUfullname
into school
, allowing future modification of school
.
...