1 Overview
Static declared variables have two features in C language:
1), the variable will be placed in the global storage area of the program, which can maintain the original assignment during the next call. This is the difference between it and the stack variable and the variable variable.
2) The variable tells the compiler with STATIC, which is visible only within the scope of the variable. This is the difference between it with global variables.
2. Question: STATIC's understanding
For Static Variables, select all the statements below:
A. If the global variable is only accessed in a single C file, you can modify this variable to a static global variable to reduce the coupling between the modules;
B, if the global variable is only accessed by a single function, this variable can be changed to the static partial variable of the function to reduce the coupling between the modules;
C, design and use access dynamic global variables, static global variables, and static local variables, need to consider re-entry issues;
D, static global variables are too large, which can cause stack overflow.
Answer and analysis:
For A, B: According to the description of this article B), we know, A, b is correct.
For C: In the description of this article a), we know that C is correct (the so-called function re-entry issues, will be described in detail below).
For D: Static variables in the global data area of the program, not allocating in the stack, so it is impossible to cause the stack overflow, and D is wrong.
Therefore, the answer is A, B, and C.
3, question: Do not enter the function
I have designed as the following function, and I am reminded when the code is checked, because this function is not retrofit, why?
Unsigned int sum_int (unsigned int found) {unsigned int index; static unsigned int sum = 0; // Note, is a Static type. For (index = 1; index <= base; index ) {SUM = Index;} returnium
Answer and analysis:
The so-called function is reusable (also predictable), ie, as long as the input data is the same, the same output should be generated.
The reason why this function is unpredictable is because the STATIC variable is used in the function, because the STATIC variable is characterized, such a function is called: a function with the "internal memory" function. So if we need a reusable function, we must avoid using Static variables in the function. The Static variable in this function is that the use principle is that it is not necessary to use it.
Modify the above function to reusable functions, as long as the static keyword in the declared sum variable is removed, the variable SUM varies to a variable of an AUTO type, the function is a reusable function.
Of course, sometimes, in the function, you must use the Static variable. For example, when a function returns a pointer type, it must be the address of the local variable of Static as the return value. If the auto type, return to be wrong. pointer.