In C language, static is used to modify variables and functions. This article introduces the main functions of static in detail. There are detailed code examples in the article. Friends who need it can refer to it.
In C language:
static is used to modify variables and functions
The main functions of static are:
1. Modified local variables - static local variables
2. Modify global variables - static global variables
3. Modified function - static function
Before explaining static variables, we should understand the difference between static variables and other variables :
call static variable static
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
operation result:
Compare the effect of code 1 and code 2 to understand the significance of static modification of local variables.
in conclusion:
Static modification of local variables changes the life cycle of variables , so that static local variables still exist outside the scope, and the life cycle ends when the program ends.
Decorate global variables
1 2 |
|
1 2 3 4 5 6 7 8 9 |
|
Code execution:
When adding a static static variable to int g_val for modification, an error occurs
Code execution:
in conclusion:
Global variables themselves have external linkage attributes
The variables defined in the A file can be used in the B file through [Link]
But if the global variable is modified by static, the external link attribute becomes an internal link attribute, and this global variable can only be used in its own source file
static can turn external link attributes into internal link attributes, making the scope of global variables smaller
modifier function
in conclusion:
The function itself has the attribute of external linkage
After being modified by static, the external link attribute becomes the internal link attribute
This function can only be used inside the source file where it is located, and other source files cannot be linked and used
This is the end of this article about the detailed explanation of static variables in C language. For more detailed explanations of C language staiic, please search for previous articles or continue to browse