Article View: comp.std.c++
Article #361Re: 'const' revisited
From: Walter Bright
Date: Wed, 15 Aug 1990 23:27
Date: Wed, 15 Aug 1990 23:27
43 lines
2157 bytes
2157 bytes
In article <56586@microsoft.UUCP> jimad@microsoft.UUCP (Jim ADCOCK) writes:
<4) Leave things the way they are now -- a muddle where people cast away from
<const, leading either to compilers that can't optimize on const, or compilers
<that do optimize on const, with "quasi-const" routines that break the
<caller's code.
This is the best solution. There are cases where the user needs to cast
away from const, even though he never changes the contents (such as in
interfacing to an existing library which doesn't use pointers to const).
As a case in point, let's try to implement an ANSI C memchr:
void *memchr(const void *p,int c,size_t n)
{ while (n--)
{ if (*(const char *)p == c)
return (void *) p; /* !!! */
p++;
}
return NULL;
}
(Note that, in ANSI C, you can use functions like memchr() to get rid
of the 'constness' of a pointer even if you disallowed the cast!
Therefore, disallowing the cast would require 2 versions of memchr(), one
for const void* and the other for void*, yeech. The ripples of this
problem go on and on...)
Casting a void* to a const void* requires an explicit cast, and so the user
is presumed to know what he's doing (just like in the rest of C).
The optimizer can presume that the contents of non-volatile const
variables do not change. If a user, by playing tricks, changes the variable,
he loses. This is similar to the case:
int a,b,*p;
b = 4;
p = &a;
c = b * 3;
p[1] = 5; /* changes b! */
d = b * 3; /* 12 is stored in d by an optimizing compiler,
15 by a non-optimizing one, though both
compilers are ANSI conforming. */
Technical Details
Message-ID:
<2648@dataio.Data-IO.COM>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!mit-eddie!uw-beaver!sumax!nwnexus!pilchuck!dataio!brightReferences:
<56514@microsoft.UUCP> <1990Aug14.125734.28015@cbnewsm.att.com> <56586@microsoft.UUCP>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!mit-eddie!uw-beaver!sumax!nwnexus!pilchuck!dataio!bright From: bright@Data-IO.COM (Walter Bright) Newsgroups: comp.std.c++ Subject: Re: 'const' revisited Keywords: const access restrictions Message-ID: <2648@dataio.Data-IO.COM> Date: 15 Aug 90 23:27:23 GMT References: <56514@microsoft.UUCP> <1990Aug14.125734.28015@cbnewsm.att.com> <56586@microsoft.UUCP> Distribution: usa Organization: Data I/O Corporation; Redmond, WA Lines: 43