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

Pointer to Constant (Pointer to const) ในภาษา C

Pointer to constant = pointer ที่ชี้ไปยังค่าคงที่ ไม่สามารถแก้ไขค่าผ่าน pointer ได้

Syntax

Data_Type const *Pointer_Name;
// หรือ
const Data_Type *Pointer_Name;

ตัวอย่าง: int const *p; // p ชี้ไป int แบบ const

โปรแกรมที่ 1: พยายามแก้ค่าผ่าน pointer to const (Error)

#include <stdio.h>
int main(void) {
    int var1 = 100;
    const int *ptr = &var1;
    *ptr = 10; // Error: cannot modify
    printf("%d\n", *ptr);
    return 0;
}

ผลลัพธ์

Compile error: assignment of read-only location

โปรแกรมที่ 2: ลบ const ออก (แก้ไขได้)

#include <stdio.h>
int main(void) {
    int var1 = 100;
    int *ptr = &var1;
    *ptr = 10; // OK
    printf("%d\n", *ptr);
    return 0;
}

ผลลัพธ์

10