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

ขอบเขตของตัวแปร (Scope) ในภาษา C

Storage class ระบุ scope, lifetime และ binding

Storage class บอก: ที่เก็บ, ค่าเริ่มต้น, scope, lifetime

Scope

Scope กำหนดความมองเห็นของวัตถุ ว่าสามารถเข้าถึงได้ที่ไหน

ตัวแปรมี scope 2 แบบ:

  • Local - ประกาศในบล็อก มองเห็นได้เฉพาะในบล็อกนั้น
  • Global - ประกาศในพื้นที่ global มองเห็นได้จากจุดประกาศจนจบโปรแกรม

ตัวอย่างที่ 1

#include <stdio.h>
int c = 30; /* global area */
int main() {
    int a = 10; // local scope
    printf("a=%d, c=%d", a, c);
    fun();
}
void fun() {
    printf("c=%d", c); // global variable
}

ผลลัพธ์

a=10, c=30
c=30

ตัวอย่างที่ 2

#include <stdio.h>
int a, b;
a = 1, b = 2;
int main() {
    int c, d;
    printf("enter c and d values:");
    scanf("%d%d", &c, &d);
    c = c + d; // local variables
    b = a * b; // global variables
    printf("c value is:%d\n", c);
    printf("b value is:%d\n", b);
    return 0;
}

ผลลัพธ์

enter c and d values: 4 7
c value is: 11
b value is: 2