You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

This is an extension of recommendation: STR30-C. Do not attempt to modify string literals

Since string literals are constant, they should only be assigned to constant pointers as indicated below:

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)
const char\* c1 = "Hello"; // Good
const char c2\[\] = "Hello"; // Good
const char c3\[6\] = "Hello"; // Good
c1\[3\] = 'a'; // Compile error

By assigning string literals to constant pointers the compiler will warn you if you try to modify them. 

Resource to use to find out more about an ongoing debate about this issue:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0389.asc 

[Lockheed Martin 2005] Lockheed Martin. Joint Strike Fighter Air Vehicle C++ Coding Standards for the System Development and Demonstration Program. Document Number 2RDU00001, Rev C. December 2005.     AV Rule 151.1

  • No labels