0

Why I have the error for the following code:

const int r = 3;
int *const ptr = &r;

However it works normaly if I define r as a plain int. As I understand, the second line only defines the pointer ptr as a const, which means that the value of this pointer cannot be changed. But why I a const pointer cannot point to a const int?

kaiyu wei
  • 431
  • 2
  • 5
  • 14
  • According to the book Cpp Primer 5th Ed. The simple trick is to read it inside-out. A `const int *ptr = &r;` can be read as a pointer that points to a constant integer. However, `int *const ptr = &r;` can be read as a constant pointer that points to an integer. In your case `r` is a constant integer but the pointer needs to point to an integer. Hope this helps :) – Programming Rage Dec 02 '21 at 08:45
  • @programmingRage Yes it helps! thank you – kaiyu wei Dec 02 '21 at 21:05

1 Answers1

3

The clockwise/spiral rule says that the definition

int *const ptr = &r;

makes ptr a constant pointer to non-constant int.

That is, while the variable ptr itself can't be modified (you can't assign to ptr), what it points to can. And that doesn't match the type of r which is constant.

If you want a constant pointer to a constant int you need:

int const* const ptr = &r;

Now neither the variable ptr can be modified, nor the data it points to.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621