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

วิธีแก้ไขค่าตัวแปร const ใน C

ตัวแปร const ไม่สามารถเปลี่ยนค่าโดยตรงได้ (Compile Error) แต่สามารถเปลี่ยนผ่าน Pointer ได้

ตัวอย่าง: พยายามเปลี่ยนโดยตรง (Error)

const int x = 10;
x = 15; // Error: assignment of read-only variable 'x'

ตัวอย่าง: เปลี่ยนผ่าน Pointer

#include <stdio.h>

int main() {
    const int x = 10;
    int *ptr = &x;
    printf("x = %d\n", x);  // 10
    *ptr = 15;              // เปลี่ยนผ่าน Pointer
    printf("x = %d\n", x);  // 15
    return 0;
}

ผลลัพธ์

x = 10
x = 15

คำเตือน: นี่เป็น Undefined Behavior ควรหลีกเลี่ยงในโค้ดจริง