c–>static关键字的使用(C — > use of static keyword)

static关键字的使用

static:静态

未使用static

在下列代码中变量a是有生命周期的,调用完后就会被销毁

所以for循环每次调用test函数打印的结果都是2

#include <stdio.h>

void test()
{
	int a = 1;
	a++;
	printf("%d", a);
}
int main(){
	for (int i = 0; i < 10; i++)
	{
		test();//打印结果2222222222
	}
	return 0;
}

使用static

在下列代码中变量a是有生命周期的,调用完后就会被销毁

在使用了static关键字后,变量的生命周期被改变了生命周期等于程序的生命周期(本质是改变了变量的存储位置,由原来的栈区改为了静态区,全局变量也是存储在静态区)

所以for循环每次调用test函数打印的结果都会+1

#include <stdio.h>

void test()
{
	static int a = 1;
	a++;//a=2
	printf("%d", a);
}
int main(){
	for (int i = 0; i < 10; i++)
	{
		test();//打印结果2,3,4,5,6,7,8,9,10,11
	}
	return 0;
}

有static关键词与extern关键词交互的情况

static修饰全局变量,使得这个全局变量只能在自己所在的源文件(.c)内部才可以使用,其他源文件不能使用*

全局变量能过被其他源文件内部使用,是因为全局变量具有外部链接属性

但是被static关键字修饰后,就变成了内部链接属性,其他源文件就不能链接到这个静态的全局变量

函数也是一样的情况

add.c

static int year = 2022;//声明全局变量

test.c(运行报错)

#include <stdio.h>
extern int  year;//使用extern关键字从add.c源文件中声明外部符号的全局变量
int main(){
	printf("%d", year);//会报错
	return 0;
}
————————

Use of static keyword

Static: static

未使用static

In the following code, variable a has a life cycle and will be destroyed after calling

So every time the for loop calls the test function, the print result is 2

#include <stdio.h>

void test()
{
	int a = 1;
	a++;
	printf("%d", a);
}
int main(){
	for (int i = 0; i < 10; i++)
	{
		test();//打印结果2222222222
	}
	return 0;
}

使用static

In the following code, variable a has a life cycle and will be destroyed after calling

After using the static keyword, the life cycle of the variable is changed. The life cycle is equal to the life cycle of the program (essentially, the storage location of the variable is changed from the original stack area to the static area, and the global variable is also stored in the static area)

Therefore, every time the for loop calls the test function, the printed result will be + 1

#include <stdio.h>

void test()
{
	static int a = 1;
	a++;//a=2
	printf("%d", a);
}
int main(){
	for (int i = 0; i < 10; i++)
	{
		test();//打印结果2,3,4,5,6,7,8,9,10,11
	}
	return 0;
}

There is interaction between static keyword and extern keyword

Static modifies a global variable so that this global variable can only be used inside its own source file (. C). Other source files cannot be used*

< strong > global variables can be used internally by other source files because they have the external link attribute < / strong >

< strong > however, after being modified by the static keyword, it becomes an internal link attribute, and other source files cannot be linked to this static global variable < / strong >

The same is true for functions

add.c

static int year = 2022;//声明全局变量

test. C (operation error)

#include <stdio.h>
extern int  year;//使用extern关键字从add.c源文件中声明外部符号的全局变量
int main(){
	printf("%d", year);//会报错
	return 0;
}