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

Variable Scoping ใน C: Static Scope (Lexical Scope)

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, PythonDynamic Scope - Lisp (บาง Dialect), Bash, Perl (local)
กำหนดโดย Source Code Structureกำหนดโดย Runtime Call Stack
Compile-time ResolvableRuntime Resolvable
Function มองเห็น Variables ใน Enclosing ScopeFunction มองเห็น Variables ของ Caller

Scope Levels ใน C

  1. File Scope (Global): นอก Function ทุกตัว, มี External Linkage (Default) หรือ Internal (static)
  2. Block Scope (Local): ใน { } (Function Body, Loop, If)
  3. Function Prototype Scope: ใน Parameter List ของ Prototype
  4. Function Scope: Label (สำหรับ goto)

Storage Duration vs Scope

Storage ClassScopeLifetimeLinkage
extern (Global)File (All Files via extern)Program DurationExternal
static (Global)File (This File Only)Program DurationInternal
static (Local)BlockProgram DurationNo Linkage
auto (Local, Default)BlockBlock DurationNo Linkage
register (Local)BlockBlock DurationNo Linkage

สรุป

C เป็น Static/Lexical Scoping Variable Visibility ถูกกำหนดโดย Source Code Structure (Compile-time) ไม่ใช่ Call Stack (Runtime) ทำให้ Code Reasoning ง่าย Compiler Optimize ได้ดี และเป็นพื้นฐานของ Modular Programming