Differences between local variables global variables local static variables and global static variables in C++

  • 2020-05-17 05:57:31
  • OfStack

Local variables (Local variables) and global variables:

Variables defined in a subroutine or block of code are called local variables, and variables defined at the beginning of program 1 are called global variables.

The global variable scope is the entire program, and the local variable scope is the subroutine or block of code that defines the variable.

When a global variable has the same name as a local variable: within the subroutine that defines the local variable, the local variable takes effect; Global variables come into play elsewhere.

Global variables carve out memory space in the program while it is running, and it is not freed until the end of the program.

To use global variables in other files, declare this variable using the extern keyword (extern int nData;) .


int nData = 10;  //  This is a 1 Global variables 
int main()
{
  int i = 0;  //  This is a 1 Local variables, this variable is only in main It works in a function. 
  int nData = 100;  //  This is also 1 Local variables, but the local variable and the global variable name, so if access nData Which one does this variable access? 
  cout << nData << endl;
  return 0;
}

The value of the output from this code is 100, because when a local variable is renamed with a global variable, the local variable is accessed. Otherwise, global variables are accessed!

Local static variables:

The local static variable is similar to global variable 1 in that it has allocated space in memory during the beginning of the program and will not be released until the end of the program.

A local static variable is defined/initialized only once, and the order is no longer defined or initialized.

Local static variables can only be accessed in defined subroutines or code blocks, not externally, so they are called local static variables.

Global static variables:

The global static variable, like the local static variable 1, allocates the memory address during the program's initial run.

The local static variable can only be accessed in the defined code block, while the global static variable can only be accessed in the defined file. Cannot be accessed across files.


Related articles: