blargg.h4g
9/28/2008 7:34:00 PM
In article
<4d3ff307-177b-466d-941b-700ba2b2a0e7@q26g2000prq.googlegroups.com>, Rahul
<rahulsharma@lucent.com> wrote:
> Hi,
> Why does the following gives a compilation error
>
> int const * * p1= 0;
> int * * p2 = 0;
> p1 = p2;
>
> p1 has more const restriction than p2 so increasing const'ness should
> always be allowed, there's no harm which p1 could do to the value
> pointed to by p2. So why is this an error.
p1 has LESS restriction in one way: *p1 = &const_int is legal, while it's
not for p2.
int* p;
int ** p2 = &p;
int const** p1 = p2; // error...
int const c = 0;
*p1 = &c;
**p2 = 1; // ...because it would allow this to modify c
See section 4.4 Qualification Conversions, paragraph 4. In summary, you
can add const (and volatile) at any "depth", as long as you also add const
to all shallower levels. As stated in the standard, this is to ensure that
const safety isn't implicitly violated. The reasoning is that when you add
it at some level, it's not there in the original type therefore if the
pointer were changed to point to a const object, the object would be
non-const in the original type and thus allow modification. Therefore,
const must be added to all shallower levels to prevent the callee from
changing anything.