I don't get the const Pointer

I've written following code:

1
2
3
4
5
int c = 5;
int const * const d = &c;
c +=1;
cout << *d; //here the Output is 6 (why?)
cout << c;  //here the Output is 6 - Which must be the case 


Why does the value of d still changes if it is constant?
Is it possible to have Pointer with a constant value which can't be changed?

It might be an easy question. But it's not so easy to understand for me. Thanks for the answer anyway.
Last edited on
When you have a pointer (or reference) to a const it simply means you are not allowed to use that pointer to modify the value.

 
*d = 5; // error 

You can still modify the value if you have some non-const access to it. If you don't want c to change you could define it as const.

1
2
int const c = 5;
int const * const d = &c;

Now you are not allowed to change the value of c.

If you don't want *d to change when c is changed you probably don't want to use a pointer. You could make d a const copy of c instead.

1
2
int c = 5;
int const d = c;

Now the value of d will always stay the same, even if c is changed.
Last edited on
Thanks a lot. I think I got the point of using pointer and const.
Topic archived. No new replies allowed.