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?

2
  • 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 :) Commented Dec 2, 2021 at 8:45
  • @programmingRage Yes it helps! thank you Commented Dec 2, 2021 at 21:05

1 Answer 1

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.

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

2 Comments

Well, I prefer to write const int *const ptr = &r;. Is there a difference between these 2 styles?
@ProgrammingRage const int is an integer which is constant, and int const is a constant integer. No difference. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.