Index
Home
About
From: torek@elf.bsdi.com (Chris Torek)
Newsgroups: comp.std.c
Subject: Re: void foo(const int *p)
Date: 25 Sep 1997 23:44:01 -0700
I think a lot of this is bogging down in a couple of different areas;
people are arguing past each other over:
- What does const mean?
- What could const mean?
- What should const mean?
Many people will produce different answers for these three.
In fact, the answer to the first, in terms of the Standard, is
`almost nothing at all'. For instance:
const int c = 3;
...
printf("%d\n", c);
could print 42, if c somehow changes despite its being declared
const. No strictly conforming program can change `c' directly,
but the object is usually subject to change through external factors
(e.g., direct writes on systems that lack memory protection, or
memory corruption from alpha particles, or whatnot). All the
Standard gets you is these two things:
- An object that is defined with `const' may not be modified
in any way by a strictly conforming program (so since `c'
above is const, it may not be modified; if it *is* modified,
the behavior is undefined).
- An lvalue with the `const'-qualifier may not be assigned-to.
This mainly buys you some compile-time typo/braino checking,
e.g., a diagnostic if you write `c = 7' instead of `v = 7'
(note that c and v are next to each other on many keyboards).
The answer to the second (`what could const mean') is quite open
ended: there are plenty of possible meanings.
The answer to the third, `what should const mean', depends on the
person asked.
Note also that the following strictly conformant program *must* print
"3, 7":
#include <stdio.h>
int v;
int *p;
void f(const int *);
int main(void) {
p = &v;
f(&v);
return 0;
}
void f(const int *vp) {
int i, j;
i = *vp;
*p = 7;
j = *vp;
printf("%d, %d\n", i, j);
}
The compiler *cannot* assume that i and j are equal, despite the
fact that *vp is const-qualified, because vp can (and does) point
to a modifiable lvalue and the assignment to *p can (and does)
modify the lvalue to which the const-qualified `vp' pointer points.
As this example illustrates, `const' does *not* mean `constant'.
--
In-Real-Life: Chris Torek, Berkeley Software Design Inc
El Cerrito, CA Domain: torek@bsdi.com +1 510 234 3167
Antispam notice: unsolicited commercial email will be handled at my
consulting rate; pyramid-scheme mail will be forwarded to the FTC.
Index
Home
About