Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!att!dptg!mtunq!psrc From: psrc@mtunq.ATT.COM (Paul S. R. Chisholm) Newsgroups: comp.std.c++ Subject: Re: casting "const" to "non-const" Summary: how would you write strchr without casting const char* to char*? Message-ID: <1211@mtunq.ATT.COM> Date: 6 Aug 90 02:54:17 GMT References: <56159@microsoft.UUCP> <56163@microsoft.UUCP> <1913@ux.acs.umn.edu> <1990Aug2.164129.25231@zoo.toronto.edu> Organization: AT&T Bell Laboratories Lines: 44 In article <1990Aug2.164129.25231@zoo.toronto.edu> henry@zoo.toronto.edu (Henry Spencer) writes: > The real, underlying problem here is precisely whether const *is* a > storage qualifier or not, by intent. Unfortunately, const gets used > for two very different purposes: "this is really, truly, a > constant" and "I may be allowed to modify this but you aren't". For example, consider the strchr function (from ANSI C): char* strchr( const char* s, int c ) and how it might be called from two functions, f1 (which takes a char* to search through), and f2 (which is passed a const char* to examine). The declaration of strchr() is intended to state that strchr() will not modify the data pointed to by its first argument. This is implemented by incrementing the pointer until it points to the appropriate character, and then casting *that* pointer from a const char* to a char*. Now, how does that affect strchr()'s callers? f1() has permission from its caller to modify the string; f2() does not. If strchr() returned a const char*, f2() would be fine, but f1() would be handed a pointer it can't use to modify the string. We could declare two polymorphic functions: const char* strchr( const char* s, int c ); char* strchr( char* s, int c) which C++ could distinguish between because of the difference in the first arguments' types; but where's the "promise" that the second function won't modify the data it's passed a pointer to? Left unspoken, for convenience's sake? > It might have been better to use different words for these two > uses. It's a bit late now. I'm afraid so. > Henry Spencer at U of Toronto Zoology, henry@zoo.toronto.edu > utzoo!henry Paul S. R. Chisholm, AT&T Bell Laboratories att!mtunq!psrc, psrc@mtunq.att.com, AT&T Mail !psrchisholm I'm not speaking for the company, I'm just speaking my mind.