一文搞懂C语言static关键字的三个作用
C语言中的static关键字是一个非常重要的关键字,有着多种用途。接下来我们来一文搞懂C语言static关键字的三个作用。
一、局部变量作用域限定
C语言中,局部变量默认是具有自动存储类型的,它的作用域仅限于它所在的代码块或函数。而在局部变量前加上static修饰符后,它的作用域就会变成整个源文件,也就是说这个变量只能在声明它的源文件中被访问。代码示例如下:
#include <stdio.h>
void example(){
static int count = 0;
count++;
printf("the count is now: %d
", count);
}
int main() {
example(); // output:the count is now: 1
example(); // output:the count is now: 2
example(); // output:the count is now: 3
return 0;
}
在上面的代码中,count变量被声明为static类型,每次调用example函数时,count的值都会被保存下来,而不是每次都重新初始化为0。这里我们可以借助static变量来实现函数内计数器或上一个函数调用的结果缓存等功能。
二、全局变量作用域限定
与局部变量作用域限定类似,static关键字也可以用来限定全局变量的作用域。我们知道,全局变量默认是具有外部链接方式的,它可以被不同的源文件访问到。但是,在全局变量加上static修饰后,它的作用域就变成了当前的源文件,其他源文件无法直接访问这个变量。代码示例如下:
// file1.c
#include <stdio.h>
static int count = 0;
void increment() {
count++;
}
void decrement() {
count--;
}
void printCount() {
printf("the count is: %d
", count);
}
// file2.c
#include <stdio.h>
void increment();
void decrement();
void printCount();
int main() {
increment();
increment();
decrement();
printCount(); // output:the count is: 1
return 0;
}
在上面的代码中,我们在file1.c文件中定义了一个static变量count,并分别定义了三个函数,这三个函数都可以访问到count变量。然后在file2.c文件中,我们通过extern声明分别调用了三个函数,来修改和输出count变量的值。由于count变量被声明为static变量,它的作用域只限于file1.c文件中,无法被其他文件访问。
三、函数作用域限定
除了可以作用于变量定义上,static关键字还可以用于函数定义上,称之为“函数作用域限定”。当函数被声明为static时,这个函数只能在当前源文件中被调用,其他源文件无法直接访问这个函数,这也就实现了函数的封装。代码示例如下:
// file1.c
#include <stdio.h>
static void greeting() {
printf("hello world
");
}
void greet() {
greeting();
}
// file2.c
// 在这个文件中无法直接调用greeting函数
#include <stdio.h>
void greet();
int main() {
greet(); // output:hello world
return 0;
}
在上面的代码中,我们在file1.c文件中定义了一个静态函数greeting,这个函数只能被file1.c文件中的其他函数调用。然后我们在file1.c文件中定义了一个非静态函数greet,它通过调用greeting函数来实现输出“hello world”的功能。在file2.c文件中,我们无法直接调用greeting函数,但可以通过调用greet函数来实现对greeting函数的间接调用。
总结
本文一共介绍了C语言static关键字的三个作用:
1. 局部变量作用域限定
2. 全局变量作用域限定
3. 函数作用域限定
在实际编程中,根据需求合理地使用static关键字可以帮助我们更好地控制变量和函数的作用域,从而实现更精细地程序设计。
