C ใช้ Static Scoping (Lexical Scoping) หมายความว่า Visibility ของ Variable ถูกกำหนดโดย ตำแหน่งใน Source Code (Textual Structure) ไม่ใช่ Runtime Call Stack (Dynamic Scoping)
ตัวอย่าง: Static Scope
#include <stdio.h>
int x = 0; // Global
int my_function() {
return x; // ใช้ Global x
}
int my_function2() {
int x = 1; // Local x (Shadows Global)
return my_function(); // เรียก my_function -> ใช้ Global x, ไม่ใช่ Local x นี้!
}
int main() {
printf("Value: %d\n", my_function2()); // Output: 0
return 0;
}
ผลลัพธ์
Value: 0
คำอธิบาย
my_function ถูก Define ใน Global Scope มัน "มองเห็น" Global x เท่านั้น เมื่อ my_function2 ประกาศ Local x มันไม่ส่งผลต่อ my_function เพราะ Scope ถูกกำหนดที่ Compile Time จาก Source Structure ไม่ใช่ Runtime Call Chain
Static vs Dynamic Scope
| Static (Lexical) Scope - C, C++, Java, Python | Dynamic Scope - Lisp (บาง Dialect), Bash, Perl (local) |
|---|---|
| กำหนดโดย Source Code Structure | กำหนดโดย Runtime Call Stack |
| Compile-time Resolvable | Runtime Resolvable |
| Function มองเห็น Variables ใน Enclosing Scope | Function มองเห็น Variables ของ Caller |
Scope Levels ใน C
- File Scope (Global): นอก Function ทุกตัว, มี External Linkage (Default) หรือ Internal (
static) - Block Scope (Local): ใน
{ }(Function Body, Loop, If) - Function Prototype Scope: ใน Parameter List ของ Prototype
- Function Scope: Label (สำหรับ
goto)
Storage Duration vs Scope
| Storage Class | Scope | Lifetime | Linkage |
|---|---|---|---|
extern (Global) | File (All Files via extern) | Program Duration | External |
static (Global) | File (This File Only) | Program Duration | Internal |
static (Local) | Block | Program Duration | No Linkage |
auto (Local, Default) | Block | Block Duration | No Linkage |
register (Local) | Block | Block Duration | No Linkage |
สรุป
C เป็น Static/Lexical Scoping Variable Visibility ถูกกำหนดโดย Source Code Structure (Compile-time) ไม่ใช่ Call Stack (Runtime) ทำให้ Code Reasoning ง่าย Compiler Optimize ได้ดี และเป็นพื้นฐานของ Modular Programming