Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ความแตกต่างระหว่าง const char* p, char * const p และ const char * const p ใน C


ตัวชี้

ในภาษาซีโปรแกรม *p แทนค่าที่เก็บไว้ในพอยน์เตอร์ และ p แทนค่าแอดเดรส เรียกว่าพอยน์เตอร์

อักขระ const* และ อักขระ const* บอกว่าตัวชี้สามารถชี้ไปที่ถ่านคงที่และค่าของถ่านที่ชี้โดยตัวชี้นี้ไม่สามารถเปลี่ยนแปลงได้ แต่เราสามารถเปลี่ยนค่าของพอยน์เตอร์ได้เนื่องจากไม่คงที่และสามารถชี้ไปที่อักขระคงที่ตัวอื่นได้

อักขระ* const บอกว่าตัวชี้สามารถชี้ไปที่ถ่านและค่าของถ่านที่ชี้โดยตัวชี้นี้สามารถเปลี่ยนแปลงได้ แต่เราไม่สามารถเปลี่ยนค่าของพอยน์เตอร์ได้ เนื่องจากตอนนี้ค่าคงที่และไม่สามารถชี้ไปที่อักขระอื่นได้

อักขระ const* const บอกว่าตัวชี้สามารถชี้ไปที่อักขระคงที่และค่าของ int ที่ชี้โดยตัวชี้นี้ไม่สามารถเปลี่ยนแปลงได้ และเราไม่สามารถเปลี่ยนค่าของพอยน์เตอร์ได้เช่นกัน ตอนนี้ค่าคงที่และไม่สามารถชี้ไปที่อักขระคงที่อื่นได้

กฎง่ายๆคือการตั้งชื่อไวยากรณ์จากขวาไปซ้าย

// constant pointer to constant char
const char * const
// constant pointer to char
char * const
// pointer to constant char
const char *

ตัวอย่าง (C)

ยกเลิกการใส่ความคิดเห็นรหัสข้อผิดพลาดที่แสดงความคิดเห็นและดูข้อผิดพลาด

#include <stdio.h>
int main() {
   //Example: char const*
   //Note: char const* is same as const char*
   const char p = 'A';
   // q is a pointer to const char
   char const* q = &p;
   //Invalid asssignment
   // value of p cannot be changed
   // error: assignment of read-only location '*q'
   //*q = 'B';
   const char r = 'C';
   //q can point to another const char
   q = &r;
   printf("%c\n", *q);
   //Example: char* const
   char u = 'D';
   char * const t = &u;
   //You can change the value
   *t = 'E';
   printf("%c", *t);
   // Invalid asssignment
   // t cannot be changed
   // error: assignment of read-only variable 't'
   //t = &r;
   //Example: char const* const
   char const* const s = &p;
   // Invalid asssignment
   // value of s cannot be changed
   // error: assignment of read-only location '*s'
   // *s = 'D';
   // Invalid asssignment
   // s cannot be changed
   // error: assignment of read-only variable 's'
   // s = &r;
   return 0;
}

ผลลัพธ์

C
E