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

ความแตกต่างระหว่าง const int*, const int * const, และ int const * ในภาษา C

Pointer

ในภาษา C ตัวดำเนินการ *p แทนค่าที่จัดเก็บใน pointer และ p แทนที่อยู่ของค่า เรียกว่า pointer

const int* และ int const* หมายถึง pointer ชี้ไปยัง int แบบคงที่ และค่าของ int ที่ถูกชี้ไม่สามารถเปลี่ยนได้ แต่สามารถเปลี่ยนค่าของ pointer เองได้ (ชี้ไปยัง constant int อื่นได้)

const int* const หมายถึง pointer ชี้ไปยัง constant int และค่าของ int ที่ถูกชี้ไม่สามารถเปลี่ยนได้ และไม่สามารถเปลี่ยนค่าของ pointer เองได้ (ชี้ไปยัง constant int อื่นไม่ได้)

กฎขมือ: อ่านไวยากรณ์จากขวาไปซ้าย

// constant pointer to constant int
const int * const
// pointer to constant int
const int *

ตัวอย่าง (C)

ลองเอาโค้ดที่คอมเมนต์ไว้ (บรรทัดที่ error) ออกมาจะเห็น error

#include <stdio.h>

int main() {
    // Example: int const*
    // Note: int const* เหมือน const int*
    const int p = 5;
    // q is a pointer to const int
    int const* q = &p;
    // Invalid assignment
    // 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 assignment
    // value of s cannot be changed
    // error: assignment of read-only location '*s'
    // *s = 7;
    // Invalid assignment
    // s cannot be changed
    // error: assignment of read-only variable 's'
    // s = &r;
    return 0;
}

เอาต์พุต

7