Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!utgpu!water!watmath!clyde!rutgers!gatech!hao!ames!oliveb!sun!guy From: guy@sun.UUCP Newsgroups: comp.lang.c Subject: Re: Literal strings in C Message-ID: <21065@sun.uucp> Date: Sun, 14-Jun-87 16:19:41 EDT Article-I.D.: sun.21065 Posted: Sun Jun 14 16:19:41 1987 Date-Received: Mon, 15-Jun-87 05:59:22 EDT References: <212@inco.UUCP> Organization: Sun Microsystems, Inc. - Mtn View, CA Lines: 68 Keywords: l-valued vs r-valued > Both of the following statements are legal, executable C, at least to > the Sun 3.2 C compiler, which is presumably based on PCC. It is. They are, in fact, legal C according to both K&R and the ANSI C draft, although the second statement may not be executable C according to the ANSI C draft. > "literal string"[i] = c; > > (This) seems utterly useless. That particular statement is unlikely to be useful, since no other occurrence of "literal string" will be modified, and thus the newly-modified value can't be accessed. The fact that you *can* do that is a consequence of the definition of character strings in C - they are just arrays of characters, and can thus be treated just like any other array - just like the fact that you can do c = i["literal string"]; (means the same thing as c = "literal string"[i]; ) is a conseqence of the definition of subscripting in C. > Does the ANSI standard address this sort of thing? 3.1.4 String literals ... A string literal has static storage duration and type ``array of "char"'', ... ...If the program attempts to modify a string literal, the behavior is undefined. Since it doesn't say ``"const" array of "char"'', I presume this means that statements of that sort are allowed, although the implementation is not required to make them work. It might be nice if C compilers were to offer an option that not only attempted to put string literals in a non-writable portion of the address space, but assigned them type "const char []", so that attempts to modify them will be caught at compile time. The function "mktemp" in UNIX overwrites the template argument it is given, but people sometimes do mktemp("/tmp/fooXXXXXX") which will overwrite the string and return a pointer to it (this means you *can* use the value of that string elsewhere), which won't work very well at all if you can't write on string literals. However, if "mktemp" were declared as char *mktemp(char *template); and string literals were of type "const char []", the compiler would rightfully complain about the conversion of "const char *" (which is what the "const char []" expression "/tmp/fooXXXXXX" would be converted to) to "char *". -- Guy Harris {ihnp4, decvax, seismo, decwrl, ...}!sun!guy guy@sun.com (or guy@sun.arpa)