penpen926
penpen926

Reputation: 115

Constant pointer to a constant int

I have just started to learn the concept "constant" in C++ and I met a problem:

int d=0;
const int* const pt = &d;
d = 3;
cout << *pt << endl;

This script gives the output of "3". The definition of pointer pt should be explained as " a constant pointer pt to a constant int" (at least I believe so). However, when I changed the value of d, the int value pointed by pt also got changed, then how can it be a "a constant pointer to a CONSTANT int" ???

Thanks very much.

Upvotes: 1

Views: 308

Answers (2)

Mat
Mat

Reputation: 206879

A pointer to const doesn't mean the target cannot change, it means you can't modify the target via that pointer.

Since what that pointer points to isn't const, it's allowed to change.

Upvotes: 5

doctorlove
doctorlove

Reputation: 19282

Without the pointer pt, you have

int d=0;
d=3;

which if fine.

If you declare d const, you can't change it:

const int d=0;
d=3; //ERROR

The pointer pt doesn't change what can be done to d. const is a promise: I won't change this, but something else might.

Upvotes: 0

Related Questions