ตัวชี้
ในภาษาซีโปรแกรม *p หมายถึงค่าที่เก็บไว้ในตัวชี้ และ p หมายถึงที่อยู่ของค่า ซึ่งเรียกว่าตัวชี้
ค่าคงที่* และ int const* บอกว่าตัวชี้สามารถชี้ไปที่ค่าคงที่ int และค่าของ int ที่ชี้โดยตัวชี้นี้ไม่สามารถเปลี่ยนแปลงได้ แต่เราสามารถเปลี่ยนค่าของพอยน์เตอร์ได้เนื่องจากไม่คงที่และสามารถชี้ไปที่ค่าคงที่อื่นได้
const int* const บอกว่าตัวชี้สามารถชี้ไปที่ค่าคงที่ int และค่าของ int ที่ชี้โดยตัวชี้นี้ไม่สามารถเปลี่ยนแปลงได้ และเราไม่สามารถเปลี่ยนค่าของพอยน์เตอร์ได้เช่นกัน ตอนนี้ค่าคงที่และไม่สามารถชี้ไปที่ค่าคงที่อื่นได้
กฎง่ายๆคือการตั้งชื่อไวยากรณ์จากขวาไปซ้าย
// constant pointer to constant int const int * const // pointer to constant int const int *
ตัวอย่าง (C)
ยกเลิกการใส่ความคิดเห็นเกี่ยวกับรหัสที่ผิดพลาดและดูข้อผิดพลาด
#include <stdio.h>
int main() {
//Example: int const*
//Note: int const* is same as const int*
const int p = 5;
// q is a pointer to const int
int const* q = &p;
//Invalid asssignment
// value of p cannot be changed
// error: assignment of read-only location '*q'
//*q = 7;
const int r = 7;
//q can point to another const int
q = &r;
printf("%d", *q);
//Example: int const* const
int const* const s = &p;
// Invalid asssignment
// value of s cannot be changed
// error: assignment of read-only location '*s'
// *s = 7;
// Invalid asssignment
// s cannot be changed
// error: assignment of read-only variable 's'
// s = &r;
return 0;
} ผลลัพธ์
7