static keyword(C语言)
1. 什么是static 关键字
- static 关键字的定义: Static is a keyword used in C programming language. It can be used with both variables and functions, i.e., we can declare a static variable and static function as well. An ordinary variable is limited to the scope in which it is defined, while the scope of the static variable is throughout the program.(我的理解就是static既能用于函数的声明当中,也能用于函数的声明当中,而且static关键字定义的变量或者函数贯穿了整个program)。
2. static 关键字注意事项
- 函数内的静态变量在调用之间保持其值
#include <stdio.h>
void foo()
{
int a = 10;
static int sa = 10;
a += 5;
sa += 5;
printf("a = %d, sa = %d\n", a, sa);
}
int main()
{
int i;
for (i = 0; i < 10; ++i)
foo();
}
打印如下:
a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
- static 关键字也可以用来修饰函数,修饰的该函数只能被用于该文件当中。
文件目录如下:
├── file1.c
├── file2.c
// file1.c
#include <stdio.h>
#include "file2.c"
void fun(){ // there is no static keyword
printf("hello");
}
int main(){
fun();
return 0;
}
//file2.c file
#include <stdio.h>
void fun(){
printf("hello");
}
//编译运行file1.c会报错如下
//err:
//goto.c:3:7: error: redefinition of 'fun'
解决该问题的方法:可以在file2.c文件里fun()函数加上static 关键字
- static 关键字定义的变量如果没有被预初始化,会被初始化为0
#include <stdio.h>
int main()
{
static int x;
int y;
printf("%d \n %d", x, y);
}
// 打印结果如下:
// 0
// [some_garbage_value]
3.static can only be seen in the scope it’s declared.
#include <stdio.h>
int main(){
{
static int a=2;
}
printf("%d",a);
return 0;
}
//这段代码运行之后会报错,请勿这样使用static关键字!!!
//static.c: In function 'main':
//static.c:6:17: error: 'a' undeclared (first use in this function)
// 6 | printf("%d",a);
// | ^
// static.c:6:17: note: each undeclared identifier is reported only once for each function it appears in
总结:不管是static修饰的变量也好,还是函数也好。只能作用在其作用域,而且static修饰的变量在其作用域当中不会随着栈帧的移动而发生变化,贯穿整个program。变量的释放不会随着作用域的结束而被释放,而是随着整个main函数结束而释放。
以上就是我对static的理解,这是博主第一个帖子,希望能帮助到大家!