Pages

Tuesday, November 29, 2011

"..never believe that "const" is some guarantee that the memory under the pointer doesn't change.." - linus torvaldus

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 

 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'.

reference : http://yarchive.net/comp/const.html [is place where i copied], it also contains the similar and more advance discussions including mail written by torvaldus throwing some insights..