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

Static Variables ใน C

Static Variables เริ่มต้นค่าเพียงครั้งเดียว คงค่าระหว่างการเรียกฟังก์ชัน มีอายุการใช้งานตลอดโปรแกรม ค่าเริ่มต้นเป็น 0

รูปแบบ

static datatype variable_name = value;

ตัวอย่างโค้ด

#include <stdio.h>

int main() {
    auto int a = -28;      // Auto (Local) Variable
    static int b = 8;      // Static Variable
    printf("The value of auto variable : %d\n", a);
    printf("The value of static variable b : %d\n", b);
    if (a != 0)
        printf("The sum of static variable and auto variable : %d\n", (b + a));
    return 0;
}

ผลลัพธ์

The value of auto variable : -28
The value of static variable b : 8
The sum of static variable and auto variable : -20

ประเภท Static Variables

ประเภทScopeLifetimeInitialization
Static Local (ในฟังก์ชัน)Local to FunctionProgram DurationOnce (First Call)
Static Global (File Scope)File (Internal Linkage)Program DurationAt Startup
Static Member (ในคลาส C++)Class ScopeProgram DurationDefinition Required

ตัวอย่าง Static Local (นับครั้งที่เรียก)

void counter() {
    static int count = 0;
    count++;
    printf("Called %d times\n", count);
}