static修饰变量



如果一个变量变static修饰,会产生什么样的结果?
(1)static修饰局部变量:
例如:
#include <stdio.h>
void test()
{
	 int a=0;//a为局部变量 
	a++;
	printf("%d",a);
}
int main ()
{
	int i=0;//i为局部变量
	for(i=0;i<10;i++)
	{
		test();
	}
	return 0;
}
运行结果为:

当a被static修饰之后:

#include <stdio.h>
void test()
{
	static int a=0;//a为局部变量 
	a++;
	printf("%d",a);
}
int main ()
{
	int i=0;//i为局部变量
	for(i=0;i<10;i++)
	{
		test();
	}
	return 0;
}
运行结果为:

即static修饰一个普通的局部变量改变了这个变量的生命周期,这个变量的生命周期和程序的生命周期相同,直到程序结束才销毁。

(2)static修饰全局变量:

在VS中新建一个项目,添加两个源文件,分别命名为1.c和2.c,

#include <stdio.h>//源文件1.c中的代码
 int a = 2018;//a为全局变量
#include <stdio.h>//源文件2.c中的代码
extern int a;
int main()
{
	printf("%d\n", a);
	return 0;
}

运行结果为:


 

当a被static修饰后:

#include <stdio.h>//源文件1.c中的代码
int a = 2018;//a为全局变量
#include <stdio.h>//源文件2.c中的代码
extern int a;
int main()
{
	printf("%d\n", a);
	return 0;
}

在调试过程中出现了错误:1.无法解析的外部命令。2.无法解析的外部符号a。

#include <stdio.h>//源文件1.c中的代码
static int a = 2018;
void test()
{
	printf("test a=%d", a);
}

#include <stdio.h>//源文件2.c中的代码
extern void test();
int main()
{
	test ();
	return 0;
}

此时运行结果为:

即static修饰全局变量

1.使得这个全局变量只能在当前源文件内使用,不能在其他源文件使用。

2.改变了全局变量的作用域。











 











  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值