1.static用来修饰全局变量
(1)当没有使用静态变量static时候,输出结果为2222222222
#include <stdio.h>
void test() { //void不需要返回
int a = 1;
a++;
printf("%d ", a);
}
int main() {
int i = 0;
while (i < 10) {
test();//引用text函数,函数名为text
i++;
}
}
分析:输出10个2是因为局部变量是有生命周期的,进入局部变量范围创建,出去就马上销毁。当i = 0时候,进入while循环执行 test( ),a=2;出 test()以后 a又变成了1。
(2)当使用静态变量static时候,输出结果为2 3 4 5 6 7 8 9 10 11
void test() { //void不需要返回
static int a = 1;//static出去不销毁
a++;
printf("%d ", a);//局部变量是有生命周期的,进入局部变量范围创建,出去马上销毁
}
int main() {
int i = 0;
while (i < 10) {
test();//引用text函数,函数名为text
i++;
}
}
总结:static修饰局部变量时候,局部变量出了作用域不销毁的;本质上,static修饰局部变量改变了变量的存储位置。影响了变量的生命周期,生命周期变长,和程序的生命周期一样。
2.static修饰全局变量
全局变量是具有外部链接属性的
* 编译+链接----->可执行程序
(1)static修饰全局变量时候,全局变量的外部链接属性变成了内部连接属性,其他源文件(.c)就不能再使用到这个全局变量。它的作用域变小了。
如以下代码是在同一个源文件中使用的,输出结果为2024
static int d_1 = 2024;
extern int d_1;//extern声明外部符号
int main() {
printf("%d\n",d_1);
return 0;
}
而如果在不同源文件中
static int d_1 = 2024;
extern int d_1;//extern声明外部符号
int main() {
printf("%d\n",d_1);
return 0;
}
这个是会显示error,要想输出来就要去掉static
3.static 修饰函数
(1)一个函数本来是具有外部链接属性的但是被static修饰的时候,外部链接属性就变成了内部链接属性。其他源文件(.c)就不能再使用到这个全局变量了。static修饰函数和修饰全局变量差不多。
static int Add(int x, int y) {
return x + y;
}
int main() {
int a = 10;
int b = 20;
int c = Add(a, b);
printf("%d\n", c);
return 0;
}
如上代码输出结果为30,若在不同的源文件中和全局变量一样,就不过多赘述。