C++ local variables, global variables, static keyword, extern keyword

  1. Local variables The variables defined inside the function
    , including the main function, are all local variables. Local variables are generally stored in the dynamic storage area, and are cleaned up after the function is executed. Variables defined in compound statements {}, that is, variables defined in curly braces { } . Local variables can have the same name as external variables. At this time, in the scope of local variables, local variables are always used

  2. Global variables Variables
    defined outside the function, that is, variables defined before the main function . The scope of a global variable is from the definition position to the end of the source program (.cpp file).
    If you want to use it in this source program but before the global variable is defined, you need to explain the extern external variable;
    if you want to use this global variable in the same project but in different source programs, you also need to explain the extern external variable;

  3. Summarize the usage of extern
    Before the global variable is defined, or if you want to use the same global variable in another source file , you need to explain it outside extern. You cannot initialize and assign values ​​when explaining. Just explain, extern A;

  4. Static usage
    1. When static limits the global variable, let the global variable be fixed in this cpp file, and other source programs cannot extern it;

    2. When static defines local variables, the local variables are no longer stored in the dynamic storage area, but in the static storage area, which is similar to global variables. It is only initialized once at compile time, and will be ignored after initialization.

    3. When static defines a function, the function becomes a static function and can only be used in the source program;

    Therefore, whether static modifies global variables, local variables or functions, they are all limited to this cpp file

Guess you like

Origin blog.csdn.net/qq_41253960/article/details/124383759