Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot initialize a variable of type 'int *const' with an rvalue of type 'const int *'

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading