简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM