Local variables and global variables in C++

In C++, the address values ​​of local variables and global variables have the following differences:

  1. storage location:

    • Local variables: Local variables are stored on the stack. Whenever a function is called, the storage space for local variables is allocated and automatically released after the function completes execution.
    • Global variables: Global variables are stored in the static data area or global data area. They exist while the program is running and are not affected by function calls and returns.
  2. life cycle:

    • Local variables: The lifetime of a local variable is limited to the scope in which it resides (usually a function). When the program flow leaves the scope, the local variables will be destroyed and their memory space will be reclaimed.
    • Global variables: The life cycle of global variables runs throughout the entire program execution process. They are created when the program starts running and destroyed when the program ends.
  3. Visibility:

    • Local variables: The scope of local variables is limited to the function or code block in which they are located. Local variables can only be accessed inside a function or code block.
    • Global variables: Global variables have global visibility and can be accessed from anywhere in the program.
  4. Address value:

    • Local variables: Each time a function is called, local variables allocate new memory space on the stack, so local variables for each function call have different address values.
    • Global variables: Global variables allocate memory space in the static data area or global data area, so they have fixed address values ​​that remain unchanged throughout the execution of the program.

There are obvious differences between local variables and global variables in storage location, life cycle, visibility and address value. Local variables are stored on the stack, have local scope and dynamic life cycle, and new memory space is allocated with each function call. Global variables are stored in the static data area or global data area, have global visibility and a static life cycle, and their address values ​​remain unchanged during program execution. Correctly understanding and distinguishing the characteristics of local variables and global variables is very important for writing maintainable and reliable programs.

Guess you like

Origin blog.csdn.net/ultramand/article/details/135009041