C | 关于局部变量和全局变量的一些思考

发布于:2023-02-10 ⋅ 阅读:(677) ⋅ 点赞:(0)

局部变量和全局变量的主要区别是其作用域生命周期不同。

从一个程序入手

local_global_variable.cpp

#include <stdio.h>
void test();

int main(void)
{
	int i = 0;
	while (i < 5) //调用test()函数5次
	{
		test();
		i++;
	}
	return 0;
	getchar();
}

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

程序运行结果为:

a = 2
a = 2
a = 2
a = 2
a = 2

a为子函数中的变量,属于局部变量,其作用域只在test() 函数中,之所以会得到上述结果,有两种理解:

a) 每次调用完子函数test() 时,a都被“丢弃”,下次调用时被重新赋值。

b) 每次调用完子函数test() 时,a被“搁置”,再次调用时使用新的值覆盖上次的值。

为了确定程序实际运行情况,对程序进行调试。

 可以发现,每次进入test() 函数后,未赋值之前,a的值均为未定义,可见a情况正确。现在将程序改为如下:

#include <stdio.h>

int main(void)
{
	int i = 0;
	while (i < 5) 
	{
		int a = 1;
		a++;
		printf("a = %d\n", a);
		i++;
	}
	return 0;
}

 程序运行结果不变,但调试结果不同,符合b情况。

在c中针对局部变量有更细致的控制,即通过static改变局部变量的生命周期。

将原始代码改为:

#include <stdio.h>
void test();

int main(void)
{
	int i = 0;
	while (i < 5) //调用test()函数5次
	{
		test();
		i++;
	}
	return 0;
}

void test(void)
{
	static int a = 1; //加入改变
	a++;
	printf("a = %d\n", a);
}

程序运行结果为:

a = 2
a = 3
a = 4
a = 5
a = 6

每次调用子函数test() 都会记忆变量a的值,且不再重新赋值。不妨再做一点改变:

#include <stdio.h>
void test();

int main(void)
{
	int i = 0;
	while (i < 5) //调用test()函数5次
	{
		test();
		i++;
	}
	return 0;
}

void test(void)
{
	static int a = 1;
	a = 1; //加入一点改变
	a++;
	printf("a = %d\n", a);
}

程序运行结果又变为:

a = 2
a = 2
a = 2
a = 2
a = 2

实际上,static也能应用于全局变量和函数,总结如下:

  • static 修饰局部变量,局部变量的生命周期变长
  • static 修饰全局变量,改变了(减小)变量的作用域,让静态的全局变量只能在自己所在的源文件内部使用,出了源文件就没法再使用了。
  • static修饰函数,改变了函数的链接属性
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到