Home > Mobile >  Const tag inconsistency (?)
Const tag inconsistency (?)

Time:06-14

Why is this legal

int i=4;
const int *l=&i;
cout<<*l;
i=6;
cout<<*l;

(shows 46)

But this isn't?

int i=4;
const int *l=&i;
*l=4;

(those 2 being the same, conceptually, from my understanding)

The way I understand those 2 examples is that both shouldn't be allowed, but the former works. Why is this?

CodePudding user response:

A pointer-to-const only promises that the pointee won't be changed using this pointer, not in general.

And even this promise can be broken without UB with const_cast, if the pointee object isn't truly const.

CodePudding user response:

You're allowed to change i, since it's not const.

When I do i = 6;, I'm assigning a value to an int, which is legal.

When I do *l = 4;, I'm assigning a value to something as though it was declared a const int, which is not legal.

All const int* l; means is that l is not allowed to change the value of the int it points to; it doesn't mean no-one is allowed to.

  •  Tags:  
  • c
  • Related