home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / std / cplus / 1994 < prev    next >
Encoding:
Text File  |  1993-01-07  |  1.6 KB  |  48 lines

  1. Newsgroups: comp.std.c++
  2. Path: sparky!uunet!taumet!steve
  3. From: steve@taumet.com (Steve Clamage)
  4. Subject: Re: initialized 'global' (extern) char arrays
  5. Message-ID: <1993Jan7.174401.8494@taumet.com>
  6. Organization: TauMetric Corporation
  7. References: <1993Jan7.032458.21941@netcom.com>
  8. Date: Thu, 7 Jan 1993 17:44:01 GMT
  9. Lines: 37
  10.  
  11. jimlynch@netcom.com (Jim Lynch) writes:
  12.  
  13. >I am given to understand that the storage allocated by
  14.  
  15. >char *x = "abcde" ;
  16.  
  17. >is not writable. In terms of whatever standard exists, is it exactly the same as
  18.  
  19. >const char *x = "abcde" ;  // ?
  20.  
  21. It is not exactly the same.  Whether literal strings are writeable is
  22. up to the implementation, not mandated by the Standard.  The sequence
  23.     char *p = "abcde";
  24.     *p = 'z';
  25. is allowed to succeed or fail.  The compiler is not obligated to warn you
  26. that you are writing to readonly storage if that is the case.  For one
  27. thing, it can't always tell.  Consider
  28.     void foo(char *q) { *q = 'z'; }
  29. This function could be called from another translation unit.  It is
  30. legal to pass such a function a pointer to a literal string, and the
  31. function doesn't know what is being passed to it.  It could fail only
  32. at run time, absent cross-module type checking.
  33.  
  34. The sequence
  35.     const char *p = "abcde";
  36.     *p = 'z';
  37. must be diagnosed as an error.  Type "const char*" is not the same
  38. type as "char *".
  39.  
  40. Three rules for happy living:
  41. 1. Don't assume you can write to literal strings.
  42. 2. Don't assign or pass a literal string to a char*.
  43. 3. Declare a parameter to be const char* if the string is only read.
  44. (Hmmm.  Maybe this is too narrow a view of happy living...)
  45. -- 
  46.  
  47. Steve Clamage, TauMetric Corp, steve@taumet.com
  48.