Search code examples
c++pointersvariablesconstants

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?


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.