ความหมายของ Scope Rules
Scope rules กำหนด:
- การเข้าถึงตัวแปร (Accessibility)
- ช่วงเวลาที่ตัวแปรมีอยู่ (Lifetime/Period of existence)
- ขอบเขตการใช้งานตัวแปร (Boundary of usage)
กฎขอบเขตสำหรับ Statement Blocks
- Block คือกลุ่มคำสั่งที่ล้อมรอบด้วย curly braces
{ } - ตัวแปรที่ประกาศใน block ใช้งานได้เฉพาะภายใน block นั้นเท่านั้น
- ตัวแปรไม่มีอยู่ภายนอก block (out of scope)
ตัวอย่างที่ 1: Blocks แยกกัน
#include <stdio.h>
int main() {
{
int i = 1;
printf("%d ", i); // ใช้ได้
}
// i ไม่มีอยู่ที่นี่
{
int j = 2;
printf("%d ", j); // ใช้ได้
}
// j ไม่มีอยู่ที่นี่
return 0;
}ผลลัพธ์
1 2
ตัวอย่างที่ 2: Redeclare ชื่อเดียวกันใน Blocks ต่างกัน
#include <stdio.h>
int main() {
{
int i = 1;
printf("%d ", i);
}
{
int i = 2; // i ใหม่ ต่างจาก i ข้างบน
printf("%d ", i);
}
return 0;
}ผลลัพธ์
1 2
คำอธิบาย: ตัวแปร i ใน block ที่สองเป็นตัวแปรใหม่ ทับซ้อน (shadow) i ตัวแรก
ตัวอย่างที่ 3: Nested Blocks - Inner Block Redeclares
#include <stdio.h>
int main() {
int i = 1;
{
int i = 2; // shadow outer i
printf("%d ", i); // พิมพ์ 2
}
// outer i ยังคงเป็น 1
return 0;
}ผลลัพธ์
2
ตัวอย่างที่ 4: Nested Blocks - Access Outer Variable
#include <stdio.h>
int main() {
int i = 1;
{
int j = 2;
printf("%d ", j); // 2
printf("%d ", i); // 1 (เข้าถึง outer i ได้ เพราะ inner ไม่มี i)
}
return 0;
}ผลลัพธ์
2 1
สรุปกฎ Scope แบบ Block
- ตัวแปรประกาศใน block ใช้ได้เฉพาะใน block นั้นและ nested blocks ภายใน (ถ้าไม่ shadow)
- Block ภายในสามารถประกาศตัวแปรชื่อเดียวกับ outer block ได้ (shadowing)
- ตัวแปร outer block เข้าถึงได้จาก inner block ถ้า inner ไม่มีตัวแปรชื่อเดียวกัน
- ตัวแปรจะถูก destroy เมื่อออกจาก block (automatic storage duration)
การประยุกต์ใช้
- จำกัดขอบเขตตัวแปร ลด bug จากการใช้ตัวแปรผิดที่
- ใช้ชื่อตัวแปรซ้ำได้ใน block ต่างกัน
- RAII pattern ใน C++ (แต่ C ไม่มี destructor)