【c语言】static修饰变量

static

1.修饰局部变量

改变了 生命周期,作用域不发生改变
eg:

void test()
{
	int i = 0;
	i++;
	printf("%d\n", i);
}


int  main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		test();
	}
	system("pause");
	return 0;
}

程序运行结果为10个1,加上static后

void test()
{
	static int i = 0;
	i++;
	printf("%d\n", i);
}


int  main()
{
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		test();
	}
	system("pause");
	return 0;
}

运行结果为:1 2 3 4 5 6 7 8 9 10
分析: static创建i,i不会被销毁,生命周期变长但是作用域并没有改变。
局部变量存在栈区,栈区数据自动创建,自动销毁,static变量存在静态区,(静态区的数据创建了但不销毁),所以static是先改变了变量的存储位置,从而改变了它的生命周期。
在这里插入图片描述

2.修饰全局变量

改变了链接属性(外->内)

3.修饰函数

改变了链接属性(外->内)

猜你喜欢

转载自blog.csdn.net/weixin_41892460/article/details/82773781