ใช้ 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* const | Const pointer to int | ไม่ได้ | ได้ |
| const int* const | Const pointer to const int | ไม่ได้ | ไม่ได้ |
const int* และ int const* **เหมือนกันทุกประการ**