Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!aplcen!samsung!sol.ctr.columbia.edu!emory!att!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: const Message-ID: <11306@alice.UUCP> Date: 7 Sep 90 15:31:30 GMT References: <10863@cadillac.CAD.MCC.COM> <142@tdatirv.UUCP> Distribution: comp Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 60 In article , cimshop!davidm@uunet.UU.NET (David S. Masterson) writes: > The point is that: > const char* substring(const char*, ...) > // first argument is important for this discussion > has a very unuseful return value (because its a constant). But if substring returns a pointer into the first argument, then the return value had better be const! > Changing it to: > char* substring(char*, ...) > makes the return value useful again, but removes the hint about what might be > optimized by the compiler (like whether its valid to place the arguments or > returns in registers). Note also that for the substring() function: > char* substring(const char*, ...) > is not possible (in this argument) because of the definition that "once a > const, always a const" (the return value will be a pointer to something in the > argument, therefore, its a const char*). Because of that definition, > overloading these last two is not possible. But the following is most certainly possible: const char* substring(const char*, const char*); char* substring(char*, const char*); and as far as I can see, it will do exactly the right thing. > The point is that in this example, you would like to use CONST on the argument > in order to make it plain that the function will not be changing the argument > (which provides optimization information for the function). However, you > don't want to use CONST on the return value because it is likely that the user > of the function will want to change the substring once substring() found it. If the argument is memory that can't be changed, and the return value is part of the argument, then the return valud had better be immutable as well. I should point out, though, that if you have a pointer to mutable memory and you convert that pointer to a pointer to const, it is entirely legitimate to cast it back. Therefore, there's no reason not to write the following: extern const char* substring(const char*, const char*); inline char* substring(char* p, const char* q) { return (char*) substring((const char*) p, q); } At first glance, one might think it unnecessary to cast p to const char*, but one would be wrong: without the cast, the result would be a recursion loop. Think about it. -- --Andrew Koenig ark@europa.att.com