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

คำสั่ง restrict ใน C: บอก Compiler ว่า Pointer ไม่ Alias กัน

restrict เป็น Keyword ใน C (C99) ใช้กับ Pointer Declaration เพื่อบอก Compiler ว่า Pointer นี้เป็นทางเข้าถึงเดียว (Unique Access) ไปยัง Object ที่ชี้อยู่ ช่วยให้ Compiler Optimize ได้ดีขึ้น

Syntax


void func(int* restrict ptr1, int* restrict ptr2, int* restrict ptr3);
// หรือ
void func(int* restrict a, int* restrict b);

ความหมายและเงื่อนไข

  • ใน Scope ของ Pointer ที่มี restrict Object ที่ชี้อยู่ ต้องไม่ถูก Access ผ่าน Pointer อื่น
  • Programmer รับผิดชอบเอง: ถ้าละเมิด → Undefined Behavior
  • ไม่เพิ่ม Functionality ใหม่ แค่ช่วย Optimization

ตัวอย่าง: การ Optimize Loop


#include <stdio.h>

// ไม่มี restrict: Compiler ต้องสมมติ a, b, c อาจ Overlap (Alias) กัน
void no_restrict(int* a, int* b, int* c, int n) {
    for (int i = 0; i < n; ++i) {
        a[i] = b[i] + c[i];
    }
}

// มี restrict: Compiler รู้ว่า a, b, c ไม่ Overlap -> Vectorize, Reorder ได้
void with_restrict(int* restrict a, int* restrict b, int* restrict c, int n) {
    for (int i = 0; i < n; ++i) {
        a[i] = b[i] + c[i];
    }
}

int main() {
    int x = 10, y = 20, z = 30;
    // เรียกใช้: Pointer ต่าง Object กันจริง -> Safe
    with_restrict(&x, &y, &z, 1);
    printf("%d %d %d\n", x, y, z); // 50 20 30
}

ผลลัพธ์

50 20 30

กรณีที่ใช้ restrict ผิด (Undefined Behavior)


int arr[10] = {0};
// ผิด: arr และ arr+1 Overlap กัน!
with_restrict(arr, arr + 1, arr + 2, 5); // UB!

C++: ไม่มี restrict Keyword (Standard)

  • GCC/Clang: __restrict__ หรือ __restrict
  • MSVC: __restrict
  • C++26: เสนอ [[assume]] Attributes แทน

เมื่อไหร่ควรใช้?

  • Function Parameters ที่เป็น Pointer Arrays ใน Numerical/Scientific Computing
  • Hot Loops ที่ต้องการ Auto-vectorization (SIMD)
  • Library APIs ที่รับ Pointer Buffers (เช่น BLAS, FFT)

สรุป

restrict เป็น Hint ให้ Compiler เพื่อ Optimization (Vectorization, Load/Store Reordering) ใช้ได้เฉพาะ C (C99) ใน C++ ใช้ Vendor Extensions (__restrict__) Programmer ต้องรับประกันว่า No Aliasing มิฉะนั้น Undefined Behavior