C 语言中的静态变量
默认情况下,C 变量 被归类为 auto 存储类型。当您希望在调用不同函数之间保留某个值时,静态变量非常有用。静态变量也用于存储在多个函数之间共享的数据。
静态变量
静态变量属于静态存储类,它们只初始化一次,并保留其值直到程序结束。使用static关键字声明静态变量。
静态变量的特性
以下是 C 编程语言中静态变量的一些特性 -
- 编译器会在计算机主内存中为静态变量分配空间。
- 与自动变量不同,静态变量被初始化为零,而不是垃圾。
- 如果静态变量在函数内部声明,则它不会在每次函数调用时重新初始化。
- 静态变量具有局部作用域。
声明静态变量变量
在 C 语言中,要声明静态变量,请使用 static 关键字并赋初值。声明静态变量的语法如下:
static datatype var = value;
此处,
- datatype 表示变量的类型,例如 int、char、float 等。
- var 是用户指定的变量名称。
- value 是用于初始化变量的任意值。默认情况下,它为零。
C 语言中静态变量的示例
示例:使用静态变量
以下是 C 语言中如何使用静态变量的示例 -
#include <stdio.h> int main(){ auto int a = -28; static int b = 8; printf("The value of auto variable: %d ", a); printf("The value of static variable b: %d ",b); if(a != 0) printf("The sum of static variable and auto variable: %d ",(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
示例:使用静态变量创建计数器函数(无需静态变量)
在本例中,x 默认为自动变量,每次调用 counter() 函数时都会初始化为 0。后续每次调用时,都会重新初始化。
#include <stdio.h> int counter(); int main(){ counter(); counter(); counter(); return 0; } int counter(){ 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: 0 Incremented value of x: 1 Value of x as it enters the function: 0 Incremented value of x: 1
但是,当 counter() 函数中的变量 x 声明为 static 时,该变量在第一次调用 counter() 函数时会被初始化为"0"。在后续每次调用中,该变量都不会重新初始化,而是保留先前的值。
示例:使用静态变量创建计数器
将"x"的声明更改为"static int x = 0;",然后再次运行程序 -
#include <stdio.h> int counter(); int main(){ counter(); counter(); counter(); return 0; } int counter(){ static int x = 0; 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
将静态变量传递给函数
您可以将静态变量传递给函数。但是,形式参数不能声明为静态,因为 C 语言将函数参数用作函数内部的局部自动变量。
示例
在此代码中,我们将一个静态变量传递给函数。但是,其值的更改不会反映在调用函数中。
#include <stdio.h> int myfunction(int x); int main(){ static int x = 5; myfunction(x); printf("in main - x:%d ", x); return 0; } int myfunction(int x){ x++; printf("Incremented value of x: %d ", x); }
输出
运行 coce 并检查其输出 −
Incremented value of x: 6 in main - x:5
静态变量和全局变量的相似之处
静态变量与全局变量具有某些相似之处。如果未显式初始化,则两者都会被初始化为"0"(对于数字类型)或"空指针"(对于指针)。
静态变量的作用域仅限于声明它的函数或代码块。这与全局变量不同,后者可在整个程序范围内访问。此外,静态变量也可以导入到另一个代码文件中,就像我们使用extern关键字一样。
示例
您也可以将全局变量声明为静态变量。请看以下示例 -
#include <stdio.h> int myfunction(); static int x = 5; int main(){ myfunction(x); printf("Inside the main function, x: %d ", x); return 0; } int myfunction(){ x++; printf("Incremented value of x: %d ", x); }
输出
运行此代码时,将产生以下输出 -
Incremented value of x: 6 Inside the main function, x: 6
最好使用静态变量,使其仅在文件内部可访问。另一方面,如果全局变量(使用 extern 声明)在其他文件中声明为 extern,则可以在程序的任何位置访问。