Changes between Version 5 and Version 6 of const


Ignore:
Timestamp:
May 13, 2010, 5:21:45 PM (10 years ago)
Author:
andersk@mit.edu
Comment:

Add a note about C library functions accepting pointers to strings.

Legend:

Unmodified
Added
Removed
Modified
  • const

    v5 v6  
    3737== `const` and strings ==
    3838
    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 *`.
     39Prehistoric 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 *`.
    4040
    4141If 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
     43String 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].
    4244
    4345== Using `const` effectively ==