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

คำสำคัญ register ในภาษา C

ตัวแปร register แจ้งคอมไพเลอร์ให้เก็บตัวแปรในรีจิสเตอร์ CPU แทนหน่วยความจำหลัก ตัวแปรที่ใช้บ่อยจะเข้าถึงได้เร็วขึ้น ไม่สามารถ取得ที่อยู่ (address) ของตัวแปร register ได้

  • ขอบเขต (Scope): ภายในฟังก์ชัน (local)
  • ค่าเริ่มต้น (Default value): ค่าขยะ (garbage value)
  • อายุการใช้งาน (Lifetime): จนจบบล็อกที่ประกาศ

ตัวอย่าง

#include <stdio.h>
int main() {
    register char x = 'S';
    register int a = 10;
    auto int b = 8;
    printf("The value of register variable b : %c\n", x);
    printf("The sum of auto and register variable : %d", (a + b));
    return 0;
}

ผลลัพธ์

The value of register variable b : S
The sum of auto and register variable : 18

สามารถใช้ register กับพอยน์เตอร์ได้ จะเก็บที่อยู่หน่วยความจำ ไม่ทำให้เกิดข้อผิดพลาด

ตัวอย่างพอยน์เตอร์

#include <stdio.h>
int main() {
    int i = 10;
    register int *a = &i;
    printf("The value of pointer : %d", *a);
    getchar();
    return 0;
}

ผลลัพธ์

The value of pointer : 10