Versions Compared

Key

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

...

As string literals are constant, they should only be assigned to constant pointers.

Non-

...

Compliant Code Example 1

The const keyword is not included in these declarations.

Code Block
bgColor#FFcccc
char* c1 = "Hello"; // Bad: assigned to non-const
char c2[] = "Hello"; // Bad: assigned to non-const
char c3[6] = "Hello"; // Bad: assigned to non-const
c1[3] = 'a'; // Undefined (but compiles)

...

Compliant Solution 1

If you properly assign string literals to const pointers, the compiler will not allow direct manipulation of the contents.

Code Block
bgColor#ccccFF
char* const c1 = "Hello"; // Good
char const c2[] = "Hello"; // Good
char const c3[6] = "Hello"; // Good
//c1[3] = 'a'; would cause a compile error

Non-

...

Compliant Coding Example 2.a

Though it is not compliant with the C Standard, this code executes correctly if the contents of CMUfullname are not modified.

Code Block
bgColor#FFcccc
char* CMUfullname = "Carnegie Mellon";

/* get school from user input and validate */

if (strcmp(school,"CMU")) {
    school = CMUfullname;
}

Non-

...

Compliant Coding Example 2.b

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 scholl after this assignment will lead to errors.

...