C语言中静态(static)关键字的作用域和生命周期是什么?
static 关键字的三种用法:
-
静态局部变量
cvoid counter() { static int count = 0; // 只初始化一次 count++; printf("Count: %d\n", count); } int main() { counter(); // Count: 1 counter(); // Count: 2 counter(); // Count: 3 } -
静态全局变量
cstatic int global_var = 100; // 文件作用域 void function() { global_var++; } // 其他文件无法访问 global_var -
静态函数
cstatic void helper_function() { printf("This is a static function\n"); } // 只能在当前文件中调用
作用域和生命周期:
-
静态局部变量
cvoid example() { // 作用域:函数内部 // 生命周期:整个程序运行期间 static int value = 10; // 每次调用都保留上次的值 value++; } -
静态全局变量
c// file1.c static int file_global = 50; // file2.c extern int file_global; // 链接错误 -
静态函数
c// file1.c static int internal_calculation(int x) { return x * 2; } // file2.c int internal_calculation(int x); // 链接错误
实际应用场景:
-
单例模式
cint* get_instance() { static int *instance = NULL; if (instance == NULL) { instance = malloc(sizeof(int)); *instance = 0; } return instance; } -
缓存机制
cint 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; } -
计数器
cint get_unique_id() { static int next_id = 0; return next_id++; } -
状态保持
cvoid 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 的区别:
- static vs const
c
// static: 控制作用域和生命周期 static int value = 10; // const: 控制可修改性 const int value = 10; // 可以组合使用 static const int CONSTANT = 100;
线程安全考虑:
-
非线程安全的静态变量
cint* get_instance_unsafe() { static int *instance = NULL; // 非线程安全 if (instance == NULL) { instance = malloc(sizeof(int)); } return instance; } -
线程安全的静态变量
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; }
最佳实践:
-
信息隐藏
c// module.c static int internal_state = 0; static void internal_helper() { internal_state++; } void public_interface() { internal_helper(); } -
避免全局变量污染
c// 使用 static 限制作用域 static int module_config = 0; void set_config(int value) { module_config = value; } -
初始化顺序
cvoid 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]; }