static keyword in C language

foreword

Static means static, so what is the use of it, let's learn about it today.

1. Modify local variables

When modifying a local variable, the local variable is out of scope and will not be destroyed. The variable life cycle becomes longer and becomes the life cycle of the entire program. Essentially, when static modifies a local variable, it changes the storage location of the variable.

memory area

If you want to understand how static changes the storage location of variables, you need to know which areas of memory there are.

Generally, we divide the process address space into three areas: stack area, heap area, and static area .

 Local variables are originally stored in the stack area, and the data in the stack area is characterized by entering the scope to create and leaving the scope to destroy.

After the local variable is modified by static, the local variable is saved in the static area. The characteristic of the static area is that it is not destroyed until the end of the program.

#include <stdio.h> void test() { static a = 1; a++; printf("%d ", a); } int main() { int i = 0; for (i = 0; i < 10; i++) { test(); } return 0; }

2. Modify global variables

When modifying a global variable, the external link attribute of the global variable becomes an internal link attribute. Other source files (.c) can no longer use this global variable.

Global variables have external linkage attributes, which can be used in other source files.

 If you modify a global variable with static, you cannot use the variable in other source files.

3. Modification function

Decorating a function has the same effect as modifying a global variable. The function also has an external link attribute. If it is modified with static, it will become an internal link attribute.

 

Guess you like

Origin blog.csdn.net/butnotif/article/details/128976326