Search code examples
c++pointersconstantstype-mismatch

Const pointer pointing to non-const data


Consider the following case 1:

const int n = 5;
int* p = &n; 

This is invalid, because &n is of type cont int* and p is of type int * (type mismatch error).

Now, consider this case 2:

int k = 4;
int *const p = &k; 

This case compiles successfully, without any error. Clearly, p is of type int * const and &k is of type int *. In this case, there is a type mismatch, but it is valid.

Question : Why is the second case valid, even though there is a type mismatch?


Solution

  • In this case, there is a type mismatch

    No; there is no type mismatch in this case. It is a pointer to non-cost and you initialise it with a pointer to non-const.

    Alternatively, if you insist on there being a "mismatch", then it is analogous to the following "mismatch":

    const int b = 42;
    

    Why is the second case valid

    Simply put: The constness of the initialiser is irrelevant to whether it initialises a const object or not. Besides, the initialiser is a prvalue of a non-class type so const qualification doesn't even apply to it.