C const correctness, restrict, volatile



const — “ห้ามแก้ผ่านชื่อนี้”

const int MAX = 100;
// MAX = 200;              // error: assignment of read-only variable

const int *p = &x;
// *p = 5;                 // error

void print_array(const int *arr, size_t n)   // ฟังก์ชันสัญญาว่าไม่แก้ arr
{
    for (size_t i = 0; i < n; i++) {
        printf("%d ", arr[i]);
        // arr[i] = 0;      // error — const ป้องกันไว้
    }
}

ตำแหน่งของ const กับ pointer — อ่านจากขวาไปซ้าย

int x = 10, y = 20;

int *p1 = &x;              // pointer แก้ได้ / ค่าแก้ได้
const int *p2 = &x;        // "pointer to const int" — ค่าแก้ไม่ได้, pointer แก้ได้
int * const p3 = &x;       // "const pointer to int" — pointer แก้ไม่ได้, ค่าแก้ได้
const int * const p4 = &x; // แก้ไม่ได้ทั้งคู่

*p2 = 5;                   // ❌ error
p2 = &y;                   // ✅ OK

*p3 = 5;                   // ✅ OK
p3 = &y;                   // ❌ error

เทคนิคอ่าน: หา * แล้วอ่านจากขวาไปซ้าย

  • const int *p — p is a pointer to int const → สิ่งที่ชี้เป็น const
  • int * const p — p is a const pointer to int → ตัว pointer เป็น const

const int * และ int const * เหมือนกัน (สลับได้)

ทำไม const ในพารามิเตอร์สำคัญ

size_t str_count(const char *s, char target);   // "ฉันแค่อ่าน s"
int    parse_int(const char *s, int *out);       // อ่าน s, เขียน *out
void   to_upper(char *s);                         // แก้ s
  • บอกผู้เรียก ว่าฟังก์ชันไม่แก้ผ่าน pointer ตัวนี้ — อ่าน API แล้วเห็นทันทีว่าตัวไหนอ่าน ตัวไหนเขียน (แต่ const parameter ไม่การันตีว่าฟังก์ชันไม่แก้ object ผ่าน alias อื่นที่ชี้ที่เดียวกัน)
  • คอมไพเลอร์บังคับ — เผลอเขียนผ่าน const parameter = compile error
  • รับ const argument ได้ — ส่ง const char * เข้าพารามิเตอร์ const char * ได้ แต่ส่งเข้า char * (non-const) ไม่ได้
str_count("hello", 'l');       // "hello" เป็น array of char — ส่งเข้า const char * ได้ และ const การันตีว่าไม่ถูกแก้

ใน C string literal เป็น array of char (ไม่ใช่ const char[] แบบ C++) — ตามกฎภาษา ส่งเข้า char * ก็ได้ (GCC เตือนเฉพาะเมื่อเปิด -Wwrite-strings) แต่ ห้ามแก้เนื้อของมัน เพราะเป็น undefined behavior จึงควรประกาศ parameter เป็น const char * เมื่อแค่อ่าน ให้คอมไพเลอร์จับตอนเผลอเขียน

แนวปฏิบัติ: ใส่ const กับ pointer parameter ทุกตัวที่ฟังก์ชันไม่แก้ — เห็นชัดในทุก API มาตรฐาน (strlen(const char *), memcpy(void *, const void *, size_t))

const กับ struct

void print_point(const Point *p)      // อ่าน p->x, p->y แต่แก้ไม่ได้
{
    printf("(%d, %d)\n", p->x, p->y);
    // p->x = 0;                       // error
}

ส่ง struct ใหญ่ by const T * — ได้ทั้งความเร็ว (ไม่ copy) และความปลอดภัย (แก้ไม่ได้)

const ไม่ใช่ “ค่าคงที่ตอนคอมไพล์”

const int n = get_size();     // n ตั้งค่าตอนรัน แค่แก้ไม่ได้หลังจากนั้น
int arr[n];                   // VLA (C99) — n ไม่ใช่ compile-time constant

#define SIZE 100              // นี่คือ compile-time constant
int arr2[SIZE];               // อาร์เรย์ปกติ

ใน C, const int ไม่นับเป็น “constant expression” สำหรับขนาดอาร์เรย์ (ต่างจาก C++) — ใช้ #define หรือ enum

volatile — “ค่าอาจเปลี่ยนนอกการควบคุม”

บอกคอมไพเลอร์ว่า อย่า optimize การอ่านตัวแปรนี้ เพราะค่าอาจเปลี่ยนจาก:

  • hardware register (embedded)
  • signal handler
  • อีก thread (แต่ volatile ไม่ใช่ เครื่องมือ thread — ใช้ _Atomic / mutex)
#include <stdio.h>
#include <signal.h>

volatile sig_atomic_t g_stop = 0;

void handle_sigint(int sig)
{
    (void)sig;
    g_stop = 1;
}

int main(void)
{
    signal(SIGINT, handle_sigint);
    while (!g_stop) {           // ถ้าไม่มี volatile คอมไพเลอร์อาจ cache g_stop
        // ... ทำงาน                เป็น 0 ตลอด แล้ว loop ไม่จบแม้กด Ctrl+C
    }
    printf("หยุดแล้ว\n");
    return 0;
}

ตัวอย่าง embedded:

volatile uint32_t *STATUS_REG = (uint32_t *)0x40001000;
while ((*STATUS_REG & 0x1) == 0) {
    // รอ bit 0 ของ register เป็น 1 — ต้องอ่านจริงทุกรอบ
}

99% ของโค้ด application ไม่ต้องใช้ volatile — ใช้เฉพาะ hardware, signal handler flag

restrict — “pointer เหล่านี้ไม่ทับกัน”

restrict (C99) สัญญากับคอมไพเลอร์ว่าข้อมูลที่ pointer สองตัวชี้ ไม่ทับกัน (no aliasing) — ทำให้ optimize ได้ดีกว่า

void add_arrays(int n, int * restrict out,
                const int * restrict a, const int * restrict b)
{
    for (int i = 0; i < n; i++) {
        out[i] = a[i] + b[i];      // คอมไพเลอร์รู้ว่า out ไม่ทับ a, b
    }
}

memcpy ใช้ restrict (ห้าม src/dest ทับกัน) — นั่นคือเหตุที่ memmove มีแยก (รองรับทับกัน)

ถ้าโกหก = UB — “ทับกัน” ในความหมายของ restrict คือ *มีการเข้าถึง object เดียวกันโดยที่อย่างน้อยหนึ่งครั้งเป็นการเขียน* ผ่าน pointer ต่างตัว (สอง const pointer ที่อ่านอย่างเดียวชี้ที่เดียวกันไม่ผิดกฎ) ใช้เมื่อมั่นใจเท่านั้น ส่วนใหญ่ปล่อยให้คอมไพเลอร์จัดการ

เรื่องที่คนมักพลาด

  • ไม่ใส่ const กับ parameter ที่แค่อ่าน — ผู้เรียกอ่าน API แล้วไม่รู้ว่าตัวไหนถูกแก้ และคอมไพเลอร์ไม่จับตอนเผลอเขียน
  • คิดว่า string literal ใน C เป็น const char[] — จริง ๆ เป็น array of char (ส่งเข้า char * ได้) แต่แก้เนื้อไม่ได้ (UB)
  • คิดว่า const parameter = ฟังก์ชันไม่แตะ object นั้นเลย — ห้ามแค่เขียน *ผ่าน pointer ตัวนั้น* ยังเขียนผ่าน alias อื่นได้
  • const int *p คิดว่า pointer แก้ไม่ได้ — แก้ค่าที่ชี้ไม่ได้ แต่ p = &other ได้ (สลับ: int * const)
  • const int n; int arr[n]; คาดว่าเป็นอาร์เรย์ปกติ — เป็น VLA (C99) ใช้ #define/enum
  • ใช้ volatile เพื่อ thread safety — ไม่พอ! ใช้ _Atomic, mutex, หรือ stdatomic.h
  • cast const ออกแล้วแก้ — *(int *)p = 5 เมื่อ p เป็น const int * ที่ชี้ไปตัวแปร const จริง — UB
  • restrict แล้ว pointer ทับกันจริง — UB, ผลลัพธ์เพี้ยนแบบหายาก

สรุป

  • const = ห้ามแก้ผ่านชื่อนี้ — ใส่กับ pointer parameter ทุกตัวที่ฟังก์ชันไม่แก้
  • const int *p = ค่าแก้ไม่ได้ (pointer ได้); int * const p = pointer แก้ไม่ได้ (ค่าได้) — อ่านขวาไปซ้าย
  • const int ≠ compile-time constant สำหรับขนาดอาร์เรย์ — ใช้ #define/enum
  • volatile = อย่า optimize การอ่าน (hardware register, signal flag sig_atomic_t) — ไม่ใช่ thread tool
  • restrict = สัญญาว่า pointer ไม่ทับกัน (optimization) — โกหก = UB

บทถัดไปว่าด้วย storage class และ lifetime — static, extern, auto, register และ linkage