C 语言中的 static 关键字
C 语言中的 static 关键字是什么?
C 语言中的 static 关键字 是存储类说明符之一,根据其使用环境的不同,其含义也有所不同。
"static"关键字用于声明静态变量以及定义静态函数。当变量声明为"static"时,它代表一个静态存储类。
静态函数仅在定义它的程序文件(扩展名为".c")内部可用。不能使用"extern"关键字将静态函数导入另一个文件。
static 关键字的用途
以下是 static 关键字的不同用法
- 静态局部变量:使用 static 关键字声明局部变量时,其生存期将持续到程序结束,并在函数调用之间保留其值。
- 静态全局变量:使用 static 关键字声明全局变量时,只能在同一文件内访问。当您想将全局变量设置为声明它的文件的私有全局变量时,它非常有用。
- 静态函数:当您将函数声明为静态函数时,其作用域将仅限于声明该函数的文件中。您无法在其他文件中访问该函数。
静态变量(带 static 关键字的变量)
当变量声明为静态变量时,它只会初始化一次。编译器会保留该变量直到程序结束。 静态变量也用于存储在多个函数之间共享的数据。
以下是一些关于静态变量需要注意的要点:
- 编译器会在计算机主内存中为静态变量分配空间。
- 与auto不同,静态变量初始化为零,而不是垃圾回收。
- 如果静态变量在函数内部声明,则它不会在每次函数调用时重新初始化。
- 静态变量具有局部作用域。
static 关键字与变量示例
在下面的示例中,counter() 函数中的变量"x"被声明为静态变量。第一次调用 counter() 函数时,它被初始化为"0"。在每次后续调用中,它不会被重新初始化;而是保留先前的值。
#include <stdio.h> int counter(); int main() { counter(); counter(); counter(); return 0; } int counter() { static int x; printf("Value of x as it enters the function: %d ", x); x++; printf("Incremented value of x: %d ", x); }
输出
运行此代码时,将产生以下输出 -
Value of x as it enters the function: 0 Incremented value of x: 1 Value of x as it enters the function: 1 Incremented value of x: 2 Value of x as it enters the function: 2 Incremented value of x: 3
静态变量与全局变量类似,因为它们都会被初始化为 0(对于数字类型)或空指针(对于指针),除非明确赋值。但是,静态变量的作用域仅限于声明它的函数或代码块。
静态函数(函数中的 static 关键字)
默认情况下,每个函数都会被编译器视为全局函数。它们可以在程序内部的任何位置访问。
在定义中添加关键字"static"前缀时,我们得到的静态函数的作用域仅限于其目标文件(以".c"扩展名保存的程序的编译版本)。这意味着该静态函数仅在其目标文件中可见。
可以在函数名称前添加关键字"static"来声明静态函数。
static 关键字与函数示例(多个文件中)
使用 CodeBlocks IDE 打开一个控制台应用程序。添加两个文件"file1.c"和"main.c"。这两个文件的内容如下 -
"file1.c"的内容 -
static void staticFunc(void) { printf("Inside the static function staticFunc() "); }
"main.c"的内容 −
#include <stdio.h> #include <stdlib.h> int main() { staticFunc(); return 0; }
现在,如果构建上述控制台应用程序项目,我们将收到错误,即"未定义对 staticFunc() 的引用"。发生这种情况是因为 staticFunc() 函数是一个静态函数,并且仅在其目标文件中可见。
static 关键字与函数示例(在同一文件中)
以下程序演示了静态函数在 C 程序中的工作原理 -
#include <stdio.h> static void staticFunc(void){ printf("Inside the static function staticFunc() "); } int main(){ staticFunc(); return 0; }
输出
上述程序的输出如下 -
Inside the static function staticFunc()
在上述程序中,函数 staticFunc() 是一个静态函数,它打印"静态函数 staticFunc() 内部"。main() 函数调用 staticFunc()。由于静态函数仅从其自身的目标文件中调用,因此该程序运行正常。
static 关键字与多个函数的示例
您可以在同一个目标文件中包含多个静态函数,如下例所示 -
#include <stdio.h> #include <stdlib.h> #include <math.h> // 定义静态函数 static int square( int num){ return num * num; } static void voidfn(){ printf ("From inside the static function. "); } static int intfn(int num2){ return sqrt(num2); } int main(){ int n1, val; n1 = 16; val = square(n1); // 调用 voidfn 静态函数 printf("The square of the %d : %d ", n1, val); voidfn(); //调用intfn静态函数 val = intfn(n1); printf("The square root of the %d : %d ", n1, val); return 0; }
输出
运行此代码时,将产生以下输出 -
The square of the 16: 256 From inside the static function. The square root of the 16: 4