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

ตัวแปร Static Local ในภาษา C คืออะไร?

ความหมายและลักษณะของ Local Static Variable

Local static variable คือตัวแปรที่ประกาศภายในฟังก์ชันด้วยคำสำคัญ static อายุการใช้งาน (lifetime) ยืดเยื้อตลอดการทำงานของโปรแกรม ไม่สิ้นสุดเมื่อฟังก์ชันจบ ทุกครั้งที่เรียกฟังก์ชัน จะใช้ตัวแปรตัวเดียวกัน (รักษาค่าไว้)

ค่าเริ่มต้น

ค่า default ของ static variable คือ 0

เปรียบเทียบขอบเขตตัวแปร

Local Variable (ปกติ)

#include <stdio.h>
main() {
    int a = 40, b = 30, sum; // อายุอยู่ในบล็อกนี้เท่านั้น
    printf("sum=%d", a + b);
}

Output: sum=70

Global Variable

int c = 30; /* global area */
main() {
    int a = 10; // local
    printf("a=%d, c=%d", a, c);
    fun();
}
fun() {
    printf("c=%d", c);
}

Output: a=10, c=30 แล้ว c=30

Local Static Variable

#include <stdio.h>

void fun() {
    static int x = 0; // default 0
    printf("%d ", x);
    x = x + 1;
}

int main() {
    fun(); // 0
    fun(); // 1
    return 0;
}

Output: 0 1

ประโยชน์: ใช้นับจำนวนครั้งที่ฟังก์ชันถูกเรียก เก็บสถานะระหว่างการเรียก