乐闻世界logo
搜索文章和话题

C语言中静态(static)关键字的作用域和生命周期是什么?

2月18日 17:18

C语言中静态(static)关键字的作用域和生命周期是什么?

static 关键字的三种用法:

  1. 静态局部变量

    c
    void counter() { static int count = 0; // 只初始化一次 count++; printf("Count: %d\n", count); } int main() { counter(); // Count: 1 counter(); // Count: 2 counter(); // Count: 3 }
  2. 静态全局变量

    c
    static int global_var = 100; // 文件作用域 void function() { global_var++; } // 其他文件无法访问 global_var
  3. 静态函数

    c
    static void helper_function() { printf("This is a static function\n"); } // 只能在当前文件中调用

作用域和生命周期:

  1. 静态局部变量

    c
    void example() { // 作用域:函数内部 // 生命周期:整个程序运行期间 static int value = 10; // 每次调用都保留上次的值 value++; }
  2. 静态全局变量

    c
    // file1.c static int file_global = 50; // file2.c extern int file_global; // 链接错误
  3. 静态函数

    c
    // file1.c static int internal_calculation(int x) { return x * 2; } // file2.c int internal_calculation(int x); // 链接错误

实际应用场景:

  1. 单例模式

    c
    int* get_instance() { static int *instance = NULL; if (instance == NULL) { instance = malloc(sizeof(int)); *instance = 0; } return instance; }
  2. 缓存机制

    c
    int expensive_calculation(int n) { static int cache[100] = {0}; if (n < 100 && cache[n] != 0) { return cache[n]; } int result = /* 复杂计算 */; if (n < 100) { cache[n] = result; } return result; }
  3. 计数器

    c
    int get_unique_id() { static int next_id = 0; return next_id++; }
  4. 状态保持

    c
    void state_machine() { static enum { INIT, RUNNING, DONE } state = INIT; switch (state) { case INIT: printf("Initializing...\n"); state = RUNNING; break; case RUNNING: printf("Running...\n"); state = DONE; break; case DONE: printf("Done!\n"); break; } }

与 const 的区别:

  1. static vs const
    c
    // static: 控制作用域和生命周期 static int value = 10; // const: 控制可修改性 const int value = 10; // 可以组合使用 static const int CONSTANT = 100;

线程安全考虑:

  1. 非线程安全的静态变量

    c
    int* get_instance_unsafe() { static int *instance = NULL; // 非线程安全 if (instance == NULL) { instance = malloc(sizeof(int)); } return instance; }
  2. 线程安全的静态变量

    c
    #include <pthread.h> int* get_instance_safe() { static int *instance = NULL; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); if (instance == NULL) { instance = malloc(sizeof(int)); } pthread_mutex_unlock(&mutex); return instance; }

最佳实践:

  1. 信息隐藏

    c
    // module.c static int internal_state = 0; static void internal_helper() { internal_state++; } void public_interface() { internal_helper(); }
  2. 避免全局变量污染

    c
    // 使用 static 限制作用域 static int module_config = 0; void set_config(int value) { module_config = value; }
  3. 初始化顺序

    c
    void function() { static int initialized = 0; static int cache[100]; if (!initialized) { for (int i = 0; i < 100; i++) { cache[i] = i * i; } initialized = 1; } return cache[10]; }
标签:C语言