Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I put a pointer to const on right hand side of assignment?

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.

like image 299
Laeeq Khan Avatar asked Aug 10 '16 04:08

Laeeq Khan


People also ask

Can a pointer be const C++?

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.

Can you change what a const pointer points to?

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.

What does const& mean in C++?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

Is this pointer is const pointer?

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.


1 Answers

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);
like image 120
songyuanyao Avatar answered Sep 19 '22 21:09

songyuanyao