Const pointer pointing to non-const data

Viewed 1300

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?

2 Answers

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.

Firstly, int *const does mean a const pointer to a non-const int. So there is absolutely no type mismatching between pointer and pointee types.

Secondly, you can always take the address of a non-const variable into a pointer to a const. So this would be valid too:

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