static的三个作用



一、修饰局部变量-静态局部变量

static修饰局部变量时,改变了变量的生命周期,让静态局部变量出了作用域依然存在,到程序结束,生命周期才结束,但是作用域不变,仍为局部作用域,当定义它的函数或者语句块结束的时候,作用域随之结束。

代码1:没有static修饰的局部变量

#include <stdio.h>
void test(){
	int i = 0;
	i++;
	printf("%d ", i);
}
int main()
{   
	int i = 0;
	for (i = 0; i < 10; i++){
		test();
	}
	system("pause");
	return 0;
}

结果:

分析:
变量i出了作用域之后,生命周期和作用域均无效。每次执行 for 循环的时候 i 都会被重新定义和初始化。


代码2:static修饰局部变量

#include <stdio.h>
void test(){
	static int i = 0;
	i++;
	printf("%d ", i);
}
int main()
{   
	int i = 0;
	for (i = 0; i < 10; i++){
		test();
	}
	system("pause");
	return 0;
}

结果:

分析:
变量i只在第一次调用的时候,创建和初始化一次,此后执行i++,每次加一。

二、修饰全局变量-静态全局变量

static修饰全局变量时,这个全局变量只能在本源文件内使用,不能在其他源文件内使用。

代码1:没有static修饰的全局变量
t.c

//t.c
int g = 2020;

test.c

//test.c
#include <stdio.h>
extern int g;
int main()
{
	printf("%d\n",g);
	system("pause");
	return 0;
}

结果:

分析:
结果是2020。


代码2:static修饰的全局变量
t.c

//t.c
static int g = 2020;

test.c

//test.c
#include <stdio.h>
extern int g;
int main()
{
	printf("%d\n",g);
	system("pause");
	return 0;
}

结果:
在这里插入图片描述
分析:
生成错误,无法解析的外部符号_g,无法解析的外部命令,被static修饰的全局变量只能在本源文件内使用,不能在其他源文件内使用。

三、修饰函数-静态函数

static修饰函数,该函数只在本文件内被调用或访问,不能跨文件访问,其他文件中可以定义相同名字的函数,不会发生冲突。

代码1:没有static修饰的函数
add.c

//add.c         
int MyAdd(int x, int y){
	return x + y;
}

s.c

//s.c
#include <stdio.h>
extern int MyAdd(int x, int y);
int main()
{
	printf("%d\n", MyAdd(1, 1));
	system("pause");
	return 0;
}

结果:

分析:
输出结果2。


代码2:static修饰的函数
add.c

//add.c
static int MyAdd(int x, int y){
	return x + y;
}

s.c

//s.c
#include <stdio.h>
extern int MyAdd(int x, int y);
int main()
{
	printf("%d\n", MyAdd(1, 1));
	system("pause");
	return 0;
}

结果:

分析:
无法解析的外部符号 _MyAdd,该符号在函数 _main 中被引用,无法解析的外部命令。被static修饰的函数只在本文件内被调用或访问,不能跨文件访问。


代码3:与被static修饰函数相同名字的函数
my.c

//my.c
int MyAdd(int a, int b){
	return a-b;
}

#include <stdio.h>
int main()
{
	printf("%d\n", MyAdd(1, 1));
	system("pause");
	return 0;
}

结果;
在这里插入图片描述分析:
static修饰函数时,其他文件中可以定义相同名字的函数,不会发生冲突。

四、总结和注意点

1.static修饰局部变量时,改变了变量的生命周期,让静态局部变量出了作用域依然存在,到程序结束,生命周期才结束,作用域仍为局部作用域。
2.static修饰全局变量时,这个全局变量只能在本源文件内使用,不能在其他源文件内使用。
3.static修饰函数时,该函数只在本文件内被调用或访问,不能跨文件访问,其他文件中可以定义相同名字的函数,不会发生冲突。
4.全局变量和函数在外部使用声明时,extern关键字是必须的,声明可以多次。

  • 43
    点赞
  • 159
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值