static 关键字.
1、static修饰局部变量;
① 整个生命周期延长,
② 静态局部变量只会被初始化一次,以后每一次调用静态局部变量,就会使用上一次调用完保存的值。
③ 只能被作用域的变量和函数访问,虽然存在于程序的整个生命周期,但不能被其他函数、文件访问。
//没有static修饰变量
#include<stdio.h>
#include<windows.h>
int func(int c){
int a = 0;
int b = 3;//修饰
int sum;
a++;
b++;
sum =a + b + c;
return sum;
}
int main()
{
int c = 1;
for (int i = 1; i <= 4;i++){
printf("%d\n",func(c));
}
system("pause");
return 0;
}
//输出结果为6
6
6
6
请按任意键继续. . .
static修饰变量;
#include<stdio.h>
#include<windows.h>
int func(int c){
int a = 0;
static int b = 3;
int sum;
a++;
b++;
sum =a + b + c;
return sum;
}
int main()
{
int c = 1;
for (int i = 1; i <= 4;i++){
printf("%d\n",func(c));
}
system("pause");
return 0;
}
//输出结果为:
6
7
8
9
请按任意键继续. . .·
2、static修饰全局变量
全局变量被static修饰,静态全局变量只能在其定义的源文件使用,在同项目的源文件内不可见。
//test1.c源文件
#include<stdio.h>
#include<windows.h>
int a = 1;
//我们在test1.c文件文件中定义一个整型变量,在test2c中使用
//test2源文件
#include<stdio.h>
#include<windows.h>
int main(){
extern int a;
printf("%d\n",a);
system("pause");
return 0;
}
//运行结果为
1
请按任意键继续. . .
//运行就会报搓
普通的全局变量对整个工程可见,其他文件可以使用extern外部声明后直接使用
下面对上述例子中的变量使用static修饰
//test1.c文件
#include<stdio.h>
#include<windows.h>
static int a = 1;
//test2.c文件
#include<stdio.h>
#include<windows.h>
int main(){
extern int a;
printf("%d\n",a);
system("pause");
return 0;
//运行结果会报错
//1>LINK : fatal error LNK1168: 无法打开 D:\c 语言\VS //code\static\Debug\static.exe 进行写入========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========
3、static 修饰函数
static修饰函数,该函数对本源文件之外的其他源文件是不可见,当函数不希望被外界所看见就用static修饰这个函数。
//test1.c文件
#include <stdio.h>
#include<windows.h>
void fun(void)
{
printf("hello\n");
system("pause");
}
//test2.c文件
#include <stdio.h>
#include<windows.h>
int main(void)
{
fun();
system("pause");
return 0;
}
//运行结果为:
hello
请按任意键继续. . .
没用static修饰函数,函数是可以被其他文件调用的
下面我们用static对上面的例子中的函数进行修饰
//test1.c文件
#include <stdio.h>
#include<windows.h>
static void fun(void)
{
printf("hello\n");
system("pause");
}
//test2.c文件
#include <stdio.h>
#include<windows.h>
int main(void)
{
fun();
system("pause");
return 0;
}
//运行就会报错
//1>D:\c 语言\VS code\static\Debug\static.exe : fatal error LNK1120: 1 个无法解析的外部命令
//此时的fun()函数只能在test1.c文件内使用,test2.c是看不见test1.c文件内的fun()函数