ค่าที่อยู่ของตัวชี้เป็นค่าคงที่ ซึ่งหมายความว่าเราไม่สามารถเปลี่ยนค่าของที่อยู่ที่ชี้โดยตัวชี้ได้
ตัวชี้คงที่ถูกประกาศดังนี้ −
Data_Type const* Pointer_Name;
ตัวอย่างเช่น int const *p// ตัวชี้ไปยังจำนวนเต็ม const
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C เพื่อแสดงตัวชี้เป็นค่าคงที่ -
#include<stdio.h> int main(void){ int var1 = 100; // pointer to constant integer const int* ptr = &var1; //try to modify the value of pointed address *ptr = 10; printf("%d\n", *ptr); return 0; }
ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Display error, trying to change the value of pointer to constant integer
ตัวอย่าง
โปรแกรม C ต่อไปนี้แสดงให้เห็นว่าจะเกิดอะไรขึ้นหากเราลบ const -
#include<stdio.h> int main(void){ int var1 = 100; // removed the pointer to constant integer int* ptr = &var1; //try to modify the value of pointed address *ptr = 10; printf("%d\n", *ptr); return 0; }
ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
10