We can’t use non-const pointer to point to a const variable as doing so will violate the const-ness of the variable as we would be able to change the value of the variable using pointer.
So, following program will not compile and give invalid conversion from 'const int*' to 'int*' compilation.
const int value{10};
int* iptr{&value};We need to create a pointer to point to a const value. We can do this as follows:
const int value{10};
const int* iptr{&value};With this, we can’t change the variable value using dereference as it is a pointer to const.
*iptr = 120; // it will fail.However, we can still reassign another address to this pointer as pointer is not const.
iptr = &anothervalue; // this will compile successfully.Similar to const references, pointer to const can point to non-const variables also,
int nonConstValue{100};
iptr = &nonConstValue;We can’t change the value using dereferencing as pointer type is pointer to const.
*iptr = 200; // it will fail.