(static --静态的)
static的三个作用
1、修饰局部变量
2、修饰全局变量
3、修饰函数
1、修饰局部变量
#include <stdio.h>
void test()
{
int n = 1;
n++;
printf("%d ",n);
}
int main()
{
int i=0;
while(i<10)
{
test();
i++;
}
return 0;
}
此时的输出值为2 2 2 2 2 2 2 2 2 2 。
#include <stdio.h>
void test()
{
static int n = 1;
n++;
printf("%d ", n);
}
int main()
{
int i = 0;
while (i < 10)
{
test();
i++;
}
return 0;
}
使用static修饰后,输出值为 2 3 4 5 6 7 8 9 10 11。
首先我们要知道局部变量存储在栈区,静态变量和全局变量存放在静态区。
在被static修饰后,局部变量的存储类型发生改变,从栈区变为静态区,而存储在静态区的变量出了它的作用域也不被销毁,生命周期被延长。
2、static修饰全局变量
全局变量有外部链接属性,而用static修饰后,全局变量的链接属性会改变,变成内部链接属性。这时static修饰的全局变量只能在本源文件(.c)中使用,其他文件无法再使用。
3、static修饰函数
首先函数也具有外部链接属性,用static修饰同样改变它的外部链接属性,变成内部链接属性。这时static修饰的函数只能在本源文件(.c)中使用,其他文件无法再使用。