Changes between Version 5 and Version 6 of const
- Timestamp:
- May 13, 2010, 5:21:45 PM (15 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
const
v5 v6 37 37 == `const` and strings == 38 38 39 For historical reasons, literal strings have type `char[]` by default. However, literal strings are still put into a read-only section of the program image, and it is invalid to modify or free one. Therefore literal strings should always be stored in a `const char *`, never in a `char *`.39 Prehistoric C compilers did not support `const`, so to maintain compatibility with old code, literal strings have type `char[]` by default. However, literal strings are still put into a read-only section of the program image, and it is invalid to modify or free one. Therefore literal strings should always be stored in a `const char *`, never in a `char *`. 40 40 41 41 If you compile with `gcc -Wwrite-strings`, literal strings will be typed `const char[]` like they should be, to prevent you from making the mistake of storing one in a `char *`. 42 43 String functions in the standard C library accept `const char *` and return `char *`, again for compatibility; this does not cause problems because of the implicit conversion from `char *` to `const char *`. (Note that abuses such as `const char *p; char *q = strstr(p, "");` are still unsafe even though they fail to be disallowed by the signature of `strstr`.) However, a few functions like `execv` that deal with ''pointers'' to strings (or arrays of strings) were forced to choose one or the other, and they take `char **` or `char *const *` rather than `const char *const *`. A cast is required to use these functions with `const char *` strings. glibc’s `getopt` is a [http://www.kernel.org/doc/man-pages/online/pages/man3/getopt.3.html#CONFORMING_TO particularly special case]. 42 44 43 45 == Using `const` effectively ==