static
能用于修饰局部变量,修饰全局变量和修饰函数。
修饰局部变量
当 static
用于修饰局部变量 时,此局部变量就成为静态局部变量 。它存储在静态存储区,生命周期是整个程序运行期,仅在第一次函数调用时初始化,后续调用函数不会重新初始化 ,而是保留上一次调用结束时的值,不过作用域依旧局限于定义它的函数内部。
#include <stdio.h>
void test() {
static int count = 0;//修饰局部变量
count++;
printf("count: %d\n", count);
}
int main() {
test(); //0+1
test(); //1+1
return 0;
}
//第一次调用 test 函数时初始化为 0 并自增为 1 输出,第二次调用时不会重新初始化为 0,而是保留 1 再自增为 2 输出。
修饰全局变量
若 static
修饰全局变量 ,该全局变量会变成静态全局变量。它存储在静态存储区,生命周期是整个程序运行期,但其作用域被限制在定义它的源文件内部 ,其他源文件无法通过 extern
关键字引用该变量,可避免不同源文件间全局变量命名冲突。
// file1.c
#include <stdio.h>
int normalGlobalVar = 10;// 普通全局变量
static int staticGlobalVar = 20;// static 修饰的全局变量
void printVars()
{
printf("Normal global variable: %d\n", normalGlobalVar);
printf("Static global variable: %d\n", staticGlobalVar);
}
// file2.c
#include <stdio.h>
extern int normalGlobalVar;// 声明外部普通全局变量
// 尝试声明外部 static 全局变量(这是错误的,会导致链接错误)
//生命周期是整个程序运行期,但其作用域被限制在定义它的源文件内部,
// extern int staticGlobalVar;
int main() {
// 可以访问普通全局变量
printf("Accessing normal global variable from file2: %d\n", normalGlobalVar);
// 调用 file1.c 中的函数
extern void printVars();
printVars();
return 0;
}
- 在
file1.c
中,normalGlobalVar
是普通全局变量 ,staticGlobalVar
是static
修饰的全局变量。生命周期是整个程序运行期,但其作用域被限制在定义它的源文件内部. - 在
file2.c
中,通过extern
关键字声明了normalGlobalVar
,可以正常访问该变量。而如果尝试使用extern
声明staticGlobalVar
并访问,会导致链接错误,因为static
修饰的全局变量作用域仅限于file1.c
文件内部。 - 模块化编程 :在大型项目中,每个源文件可以使用
static
全局变量来存储该模块内部需要共享的数据,避免对其他模块产生影响。 - 数据隐藏 :如果某个全局变量只在一个源文件中使用,为了防止其他文件误操作或访问,可以将其声明为
static
全局变量。
修饰函数
当 static
修饰函数时,该函数成为静态函数,其作用域被限制在定义它的源文件内部 ,其他源文件无法调用此函数 ,有助于实现信息隐藏,将函数实现细节封装在源文件内,提高程序模块化程度。
// file1.c
#include <stdio.h>
static void staticFunc()
{
printf("This is a static function.\n");
}
// file2.c
void callStaticFunc()
{
staticFunc();
}
// extern void staticFunc(); 尝试声明外部静态函数(这是错误的,会导致链接错误)
,因为 static void staticFunc()的作用域仅限于 file1.c
文件内部。