Why can't I put const int *cp1
, on the right hand side of an assignment? Please see this sample
int x1 = 1;
int x2 = 2;
int *p1 = &x1;
int *p2 = &x2;
const int *cp1 = p1;
p2 = p1; // Compiles fine
p2 = cp1; //===> Complilation Error
Why do I get error at the indicated location? After all I am not trying to change a constant value, I am only trying to use a constant value.
Am I missing something here.
A pointer to a const value (sometimes called a pointer to const for short) is a (non-const) pointer that points to a constant value. In the above example, ptr points to a const int . Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant.
A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
C++ Constant Pointers to constants: In the constant pointers to constants, the data pointed to by the pointer is constant and cannot be changed. The pointer itself is constant and cannot change and point somewhere else.
After all I am not trying to change a constant value
Implicit conversion from "pointer to const" to "pointer to non-const" is not allowed, because it'll make it possible to change a constant value. Think about the following code:
const int x = 1;
const int* cp = &x; // fine
int* p = cp; // should not be allowed. nor int* p = &x;
*p = 2; // trying to modify constant (i.e. x) is undefined behaviour
BTW: For your sample code, using const_cast
would be fine since cp1
is pointing to non-const variable (i.e. x1
) in fact.
p2 = const_cast<int*>(cp1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With