Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In the following noncompliant code, the const keyword has been omitted.

Code Block
bgColor#FFcccc
langc
char *c = "Hello";

Wiki Markup
If a statement, such as {{c\[0\] = 'C'}}, were placed following the declaration in the noncompliant code example, the code is likely to compile cleanly, but the result of the assignment is undefined because string literals are considered constant.

...

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
bgColor#ccccFF
langc
const char *c = "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
bgColor#ccccFF
langc
char c[] = "Hello";

Wiki Markup
Consequently, a statement such as {{c\[0\] = 'C'}} is valid and behaves as expected.

...

In the following noncompliant code, the const keyword has been omitted.

Code Block
bgColor#FFcccc
langc
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.

...

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
bgColor#ccccFF
langc
wchar_t const *c = L"Hello";

...

In cases where the string is meant to be modified, use initialization instead of assignment. In this compliant solution, c is a modifiable wchar_t array which has been initialized using the contents of the corresponding string literal.

Code Block
bgColor#ccccFF
langc
wchar_t c[] = L"Hello";

Wiki Markup
Consequently, a statement such as {{c\[0\] = L'C'}} is valid and behaves as expected.

...