...
Otherwise, do not attempt to modify the contents of the array.
Exceptions
EXP05-C-EX1: An exception to this recommendation is allowed when it is necessary to cast away const when invoking a legacy API that does not accept a const argument, provided the function does not attempt to modify the referenced variable. For example, the following code casts away the const qualification of INVFNAME in the call to the audit_log() function.
| Code Block |
|---|
/* Legacy function defined elsewhere—cannot be modified */
void audit_log(char *errstr) {
fprintf(stderr, "Error: %s.\n", errstr);
}
/* ... */
const char INVFNAME[] = "Invalid file name.";
audit_log((char *)INVFNAME); /* EXP05-EX1 */
/* ... */
|
EXP05-C-EX2: A number of C standard library functions are specified to return non-const pointers that refer to their const-qualified arguments. When the actual arguments to such functions reference const objects, attempting to use the returned non-const pointers to modify the const objects would be a violation of EXP40-C. Do not modify constant objects and would lead to undefined behavior. These functions are the following:
...
| Code Block |
|---|
extern const char s[]; long x; char* end; x = strtol(s, &end, 0); /* Modifying **end is undefined */ |
EXP05-C-EX3: Because const means "read-only," and not "constant," it is sometimes useful to declare struct members as (pointer to) const objects to obtain diagnostics when the user tries to change them in some way other than via the functions that are specifically designed to maintain that data type. Within those functions, however, it may be necessary to strip off the const qualification to update those members.
...