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

Scope Rules ของฟังก์ชันใน C: Local vs Global Variables

Scope rules กำหนด: เข้าถึงตัวแปรได้ที่ไหน, อายุของตัวแปร, ขอบเขตการใช้งาน

กฎขอบเขตฟังก์ชัน

  • ตัวแปรใน function = local variable ใช้ได้แค่ในฟังก์ชันนั้น
  • สิ้นสุดเมื่อฟังก์ชัน return
  • ฟังก์ชันอื่นและ main เข้าถึงไม่ได้

ตัวอย่างที่ 1: Call by Value (Local Variables)

#include <stdio.h>
void swap(int a, int b) {
    int c = a; a = b; b = c; // swap local copies
}
main() {
    int a = 10, b = 20;
    printf("Before: a=%d b=%d\n", a, b);
    swap(a, b);
    printf("After: a=%d b=%d\n", a, b); // ไม่เปลี่ยน
}

ผลลัพธ์

Before: a=10 b=20
After: a=10 b=20

ตัวอย่างที่ 2: Global Variables

#include <stdio.h>
int a = 10, b = 20; // global
void swap() {
    int c = a; a = b; b = c; // swap global
}
main() {
    printf("Before: a=%d b=%d\n", a, b);
    swap();
    printf("After: a=%d b=%d\n", a, b); // เปลี่ยนจริง
}

ผลลัพธ์

Before: a=10 b=20
After: a=20 b=10