...
By assigning string literals to constant pointers the compiler will warn you if you try to modify themdisallow you from modifying the contents directly.
Making code reverse compatible to fit this standard sometimes breaks functionality but this is a good recommendation to follow on new code. An example of a situation where implementing this would break prior code is if a string literal is assigned to a non-const pointer as in the following example
Before changing string literals to constant pointers
...
A compliant fix to this problem would be to copy the contents of "CMUfullname" to "school" but this involves the extra step of making sure school has the appropriate storage to hold it.
Code Block | ||
---|---|---|
| ||
const char* CMUfullname = "Carnegie Mellon"; ... //take user input to determine string variable "school" ... if(strcmp(school,"CMU")==0) { strcpy(school,CMUfullname); } |
...