C语言----C语言中static的用法
  TEZNKK3IfmPf 2023年11月14日 60 0

使用static修饰局部变量

(1)首先看如下代码,test函数中的变量a未使用static修饰,从执行结果可以看出,每次调用test函数的时候,a都会重新初始化

#include <stdio.h>

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

int main()
{
     
       
	int i = 0;
	while (i < 5)
	{
     
       
		test();
		i++;
	}
}

执行结果为:

a = 1
a = 1
a = 1
a = 1
a = 1

(2)下面的代码,即对test函数中a变量使用static声明,通过结果可以发现,在后续的调用test的函数的时候,并没有每次都去初始化a,通过调试可以发现,除了第一次调用test之外,后面每次调用test,都会直接跳过使用static声明a的这一行代码

#include <stdio.h>

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

int main()
{
     
       
	int i = 0;
	while (i < 5)
	{
     
       
		test();
		i++;
	}
}

执行结果如下:

a = 1
a = 2
a = 3
a = 4
a = 5

(3)结论:

使用static声明局部变量,实质是延长了变量a的声明周期

使用static修饰全局变量

(1)首先看如下代码,即没有static修饰时的全局变量的使用,创建两个.c文件,如test.c和test2.c,首先在test1.c中定义一个全局变量

int age=20;

然后在test.c文件中编写如下代码,即在test.c文件中声明age为外部变量,然后直接调用age

#include <stdio.h>


int main()
{
     
       
	extern int age;
	printf("age=%d\n", age);
	return 0;
}

test.c执行结果为:

age=20

然后再test2.c中对全局变量age使用static修饰,test2.c代码如下:

static int age = 20;

test.c保持不变,然后执行test.c,此时报如下错误,即此时已经找不到全局变量age了

error LNK2001: 无法解析的外部符号 _age

(2)结论

对全局变量使用static修饰后,则此变量仅可以在当前文件中使用,即减小了变量的作用域范围

使用static修饰函数

(1)首先看在不适用static修饰的时候的情况,创建两个文件,在test2.c中编写如下函数,未使用static修饰

int add(int x, int y)
{
     
       
	return x + y;
}

然后在test.c文件中编写如下代码

#include <stdio.h>


int main()
{
     
       
	extern int add(int, int);
	int sum = add(100, 200);
	printf("sum= %d\n", sum);
	return 0;
}

执行test.c的结果为:

sum= 300

(2)然后对test2.c文件中的add函数使用static修饰,即:

static int add(int x, int y)
{
     
       
	return x + y;
}

test.c中的代码不做修改,此时运行会出现如下错误,即此时在test.c文件中函数add也变为不可见了

error LNK2019: 无法解析的外部符号 _add,该符号在函数 _main 中被引用

(3)结论:
使用static修饰函数跟修饰全局变量的作用类似的,即当一个函数被static修饰后,在此函数的作用域即被修改为仅对当前文件可见,在其他文件中则不可以继续调用了

static使用总结

  • static修饰局部变量,可以延长局部变量的声明周期,带有static修饰的行只会执行一次
  • static修饰全局变量,缩小了全局变量的作用域范围,修改为仅在当前文件中可见
  • static修饰函数,同样缩小了函数的作用域范围,修改为此函数仅对当前文件可见
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年03月29日   103   0   0 c语言字符
  TEZNKK3IfmPf   2024年03月30日   149   0   0 C++c语言
  TEZNKK3IfmPf   2024年04月19日   54   0   0 进程c语言
TEZNKK3IfmPf