zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

C语言中 static 的使用

2023-04-18 16:05:43 时间

我的小态度:慢慢来比较快哟
欢迎大家来看我的文章
有不对的地方,麻烦大家评论区指正出来呀,谢谢大家啦


前言

关键字static
在C语言中:static是用来修饰变量和函数的
1.修饰局部变量——静态局部变量
2.修饰全局变量——静态全局变量
3.修饰函数——静态函数


一、static修饰局部变量——静态局部变量

结论:static 修饰局部变量改变了变量的生命周期,让静态局部变量出了作用 域依然存在,到程序结束,生命周期才结束。
static 本质上是改变了变量的存储类型,从栈区到了静态区。

(拓展:内存被划分为三个区域:
1.栈区:存放 局部变量、函数的参数等局部的、临时的变量
2.堆区:动态内存分配的
3.静态区:全局变量、static修饰的静态变量)

没有 static 修饰 局部变量 i

void test()
{
	int i = 0;       //没有 static 修饰局部变量 i
	i++;
	printf("%d	", i);
}

int main()
{
	int a = 0;
	while (a <= 9)
	{
		test();
		a++;
	}
	return 0;
}             //输出结果:1 1 1 1 1 1 1 1 1 1 

有 static 修饰 局部变量 i

void test()
{
	static int i = 0;      //static 修饰 局部变量 i
	i++;
	printf("%d	", i);
}

int main()
{
	int a = 0;
	while (a <= 9)
	{
		test();
		a++;
	}
	return 0;    // 输出结果:1 2 3 4 5 6 7 8 9 10
}

二、static修饰全局变量——静态全局变量

结论:一个全局变量被static修饰,使得这个全局变量只能在本源文件内使用,不能在其他源文件中使用。(同一个项目中的其他源文件内都不可使用)

全局变量,在其他源文件内部可以被使用,是因为全局变量具有外部链接属性,但是被static修饰之后,就变成了内部链接属性,其他源文件就不能链接到这个静态的全局变量了。

没有 static 修饰 全局变量 a
代码如下在这里插入图片描述

同一工程的源文件: 1.c
int a = 0;        //static 没有修饰 全局变量 a

同一工程的源文件: 2.c
#include<stdio.h>
extern int a;     
int main()
{
	printf("%d
",a);
	return 0;       //输出结果:0
}

有 static 修饰 全局变量 a

在这里插入图片描述

 同一工程的源文件: 1.c
static int a = 0;        //static 没有修饰 全局变量 a
                         //变量 a 只能在源文件 1.c 中使用

同一工程的源文件: 2.c
#include<stdio.h>
extern int a;     
int main()
{
	printf("%d
",a);
	return 0;           //无法输出结果,报错:变量a 为外部变量
}

三、static修饰函数——静态函数

总结:一个函数被static修饰,使得这个函数只能在本源文件内使用,不能在其他源文件内使用。
本质:static是将函数的外部链接属性变成了内部链接属性,和static修饰全局变量一样

没有 static 修饰 函数
在这里插入图片描述

同一个项目的源文件 1.c
int test()           //没有 static 修饰 函数
{
	int a = 0;
	return a;
}

同一个项目的源文件 2.c
int main()
{
	int b=test();
	printf("%d", b);
	return 0;       //输出结果:0
}

有 static 修饰 函数
在这里插入图片描述

同一个项目的源文件 1.c
extern static int test()    //有 static 修饰 函数
{
	int a = 0;
	return a;
}
同一个项目的源文件 2.c
int main()
{
	int b=test();
	printf("%d", b);
	return 0;           //无法输出结果
}