Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ความแตกต่าง const int*, const int* const, int const*

ใช้ Clockwise/Spiral Rule อ่านจากตัวแปรไปทางขวา (clockwise) เพื่อเข้าใจความหมาย

1. const int* (หรือ int const*)

Pointer to const int - ชี้ไปที่ int ที่ไม่สามารถแก้ไขได้ ผ่าน pointer นี้

const int* p; // หรือ int const* p
int x = 10;
p = &x;    // OK: เปลี่ยน address ได้
*p = 20;   // Error: ไม่สามารถแก้ค่าที่ชี้ได้

2. int* const

Const pointer to int - Pointer ที่ไม่สามารถเปลี่ยน address ได้ แต่แก้ค่าที่ชี้ได้

int* const p = &x;
p = &y;    // Error: ไม่สามารถเปลี่ยน address
*p = 20;   // OK: แก้ค่าที่ชี้ได้

3. const int* const (หรือ int const* const)

Const pointer to const int - ทั้ง pointer และค่าที่ชี้ ต่างไม่สามารถแก้ไขได้

const int* const p = &x;
p = &y;    // Error
*p = 20;   // Error

สรุป

DeclarationความหมายPointer เปลี่ยนได้?Value เปลี่ยนได้?
const int* / int const*Pointer to const intได้ไม่ได้
int* constConst pointer to intไม่ได้ได้
const int* constConst pointer to const intไม่ได้ไม่ได้

const int* และ int const* **เหมือนกันทุกประการ**