0

I am new to C++ and just started learning pointers. If I write the code -

    const int n = 4;
    int m = 4;
    const int *p = &n;

I understood this much that const makes the variable unchangeable. So if I want to change n, I cannot, but what value is the pointer having that is unchangeable? Because the next code is executing propery -

p = &m;

Shouldn't this give an error since it was already storing the value of n in the first place? I am sorry if it is a dumb question.

1
  • 1
    const int *p = &n; you can change the address, but you cannot change the value. So, *p = 8; will give you error. Commented Dec 25, 2020 at 7:12

1 Answer 1

0
 const int *p = &n;

The pointer above is not unchangeable, what it is pointing to is unchangeable

 const int * const cp = &n;
 cp = &m;                     // error here

This pointer is unchangeable. To make a pointer unchangeable put const after the *.

It seems the most important lesson about pointers (and one that I see beginners get confused about all the time) is the the pointer, and what it is pointing at are two separate things. In this case either the pointer or what it is pointing at can be const (or both can be).

Sign up to request clarification or add additional context in comments.

1 Comment

Another common misconception is that if you have a const T * the pointed-to object cannot be changed but in general this is false. What is true is that cannot be changed using that pointer but can still change because of aliasing (there can be other ways to access that object). See the Rect example in stackoverflow.com/a/4705871/320726 for the kind of damage this misconception can create.