1. Static global variables (also called global static variables):
(1) The definition of a static global variable: Add a static to the global variable so that the variable is available only in this source file.
(2) The difference between global variables and global static variables:
(a) If a program is composed of a source file, the global variable is not different from the global static variable.
(b) When a program is composed of multiple source files, the global variable differs from the global static variable: The global static variable makes the variable the source file that defines the variable, i.e. the global static variable is not valid for the other source files that make up the program.
(3) The role of static global variables:
(a) Do not worry about other source files using the same variable name, independent of each other.
(b) A static global variable defined in a source file cannot be used or modified by another source file.
For example, a program consists of two source files, in which "int n;" is defined in one source file, and "static int n" is defined in another source file. The program assigns different spaces to each of them, and two values do not interfere with each other.
For example: The following declares the global variable N in file1.cpp and the global static variable N in File2.cpp. Files File1.cpp and file2.cpp can be compiled individually, but when connected, the variable N in file1.cpp cannot be defined, resulting in a connection error.
File1.cpp
# include <iostream.h>
VOID Fn ()
extern int n;
void Main ()
{
n=20;
cout < <n < <endl;
FN ();
}
File2.cpp
# include <iostream.h>
static int n; The default is initialized to 0, and note that the n defined here can only be used in file2.cpp.
VOID Fn ()
{
n++;
cout < <n < <endl;
}
2, static function: Make a function only in one source file valid, cannot be used by other source files.
Definition: Add static before the function.
Description: The declaration and definition of a function is extern by default throughout the program.
Effects of static functions:
(1) It allows other source files to establish and use functions with the same name, without conflicting with each other.
(2) A function declared as static cannot be called by another source file because its name cannot be obtained.
Static Flag Statics