บทความนี้เน้นรายละเอียดเฉพาะของ Local Scope** และ Global Scope** พร้อมตัวอย่างการซ้อน Block (Nested Blocks)
Global Scope
ตัวแปรประกาศนอกฟังก์ชันทุกตัว → เข้าถึงได้ทุกฟังก์ชันในไฟล์
#include <stdio.h>
int c = 30; // Global
void fun() {
printf("In fun: c = %d\n", c);
}
int main() {
int a = 10; // Local to main
printf("In main: a = %d, c = %d\n", a, c);
fun();
return 0;
}
ผลลัพธ์
In main: a = 10, c = 30 In fun: c = 30
Local Scope
ตัวแปรใน Block { } → เข้าถึงได้เฉพาะใน Block นั้น
#include <stdio.h>
int main() {
int i = 1; // Local to main's block
printf("%d ", i);
{ // Nested Block
int j = 2; // Local to this block
printf("%d ", j);
}
// j ไม่เข้าถึงได้ที่นี่
return 0;
}
ผลลัพธ์
1 2
Variable Shadowing (การซ้อนชื่อตัวแปร)
ตัวแปรใน Block ภายในสามารถใช้ชื่อเดียวกับ Block ภายนอกได้ → ตัวในบังตัวนอก
#include <stdio.h>
int main() {
{
int i = 1;
printf("%d ", i); // 1
}
{
int i = 2; // ตัวแปรคนละตัว!
printf("%d ", i); // 2
}
return 0;
}
ผลลัพธ์
1 2
Shadowing ใน Block ซ้อน
#include <stdio.h>
int main() {
int i = 1; // Outer
{
int i = 2; // Inner shadows outer
printf("%d ", i); // 2
}
// Outer i ยังคงเป็น 1
return 0;
}
ผลลัพธ์
2
เข้าถึงตัวแปร Outer จาก Inner Block
ถ้า Inner Block ไม่ประกาศตัวแปรชื่อซ้ำ → เข้าถึง Outer ได้
#include <stdio.h>
int main() {
int i = 1; // Outer
{
int j = 2; // Inner's own
printf("%d ", j); // 2
printf("%d ", i); // 1 (เข้าถึง Outer ได้)
}
return 0;
}
ผลลัพธ์
2 1
สรุปกฎ Shadowing
- ค้นหาตัวแปรจาก Block ในนอกสุด (Innermost)
- หาไม่เจอ → ค่อยขึ้น Block ภายนอก (Enclosing Scope)
- เจอ → ใช้ตัวนั้น (Shadowing เกิดขึ้น)
- หาไม่เจอจน Global → Error: Undeclared
แนวทางปฏิบัติ
- หลีกเลี่ยง Shadowing (ใช้ชื่อไม่ซ้ำ) เพื่อความชัดเจน
- เปิด Compiler Warning:
-Wshadow(GCC/Clang) - Global Variable ควรมี Prefix:
g_หรือglobal_