The difference between a static global variable and a normal global variable

  • 2020-04-02 01:43:27
  • OfStack

(1) what is the difference between a static global variable and a normal global variable?
(2) what is the difference between static local variables and ordinary local variables?
(3) what is the difference between the scope of static function and normal function?
(4) what's the difference between a static function and a normal function?

(1) what is the difference between a static global variable and a normal global variable?
A: A static global variable is defined by adding static to it. Global variables are themselves statically stored, and static global variables are of course statically stored. The two are no different in the way they are stored. The difference between the two is that the scope of non-static global variables is the entire source program, and when a source program is composed of multiple source files, the non-static global variables are valid in each source file. A static global variable limits its scope, meaning that it is only valid in the source file where the variable is defined and cannot be used in other source files in the same source program. Since the scope of static global variables is limited to one source file and can only be Shared by functions in that source file, you can avoid causing errors in other source files. From the above analysis, it can be seen that changing a local variable to a static variable changes its storage mode, that is, its lifetime. Changing a global variable to a static variable changes its scope and limits its use.

(2) what is the difference between static local variables and ordinary local variables?
A: Static local variables are initialized only once, the next time according to the previous result value;

(3) what is the difference between the scope of static function and that of ordinary function?
A: Only in this document. Functions that are used only in the current source file should be declared as internal (static), and internal functions should be declared and defined in the current source file. For functions that can be used outside the current source file, it should be stated in a header file that the source file to use the functions contains.

(4) what's the difference between a static function and a normal function?
A: The static function has only one copy in memory, the normal function maintains a copy of the program's local variables in each call (the stack), the global variables in (the static area), and the dynamic application data in (the heap).


Related articles: