The usage and principle of C language static keyword when modifying variables and functions

Table of contents

1. The static keyword modifies local variables

2. The static keyword modifies global variables

 3. static keyword modifier function


1. The static keyword modifies local variables

In memory, it is often divided into three blocks, the stack area, the heap area, and the static area . The local variables defined in the C language, including function parameters, are stored in the stack area , but when the local variable is modified statically , the storage attribute of the variable is changed , and the variable modified by static is stored in the static area .

 The variables stored in the static area will not be destroyed when they go out of scope . The life cycle of static variables is the life cycle of the program .

When the program ends, the static variable will be reclaimed space

Example:

1. When not modified by the static keyword

 code:

#include<stdio.h>

void test()
{
	int a = 1;        //未被static修饰
	a++;
	printf("%d", a);
}
int main()
{
	int i = 10;
	while (i--)
	{
		test();
	
	}
}

2. When modified by the static keyword

code:

#include<stdio.h>

void test()
{
	static int a = 1;  //被static修饰
	a++;
	printf("%d,", a);
}
int main()
{
	int i = 10;
	while (i--)
	{
		test();
	
	}
}

    It can be seen from the above that the scope of local variables modified by static remains unchanged, and the life cycle is extended to the end of the program.

2. The static keyword modifies global variables

Global variables have an external link attribute. When the static keyword modifies a global variable , the external link attribute of the global variable becomes an internal link attribute and cannot be called by a .c file other than itself     

1. Before being modified by static:

2. After being modified by static 

 3. static keyword modifier function

The function itself also has an external link attribute . If it is modified by static , the external link attribute will become an internal link attribute and cannot be called by a .c file other than itself. (Another noteworthy point is placed in the third place below)

1. Not modified by the static keyword

2. After being modified by the static keyword

 3. It is also worth noting that when the static keyword in the external file modifies the a_static() method (custom), defining a file with the same name in the original file will not be affected by it

Guess you like

Origin blog.csdn.net/qq_64293926/article/details/125843088