There are two separate concepts here:
- the area in which it is determined where the name can be accessed, and
- storage duration, which determines when a variable is created and destroyed.
Local variables (pedantically, variables with a block area) are available only in the code block in which they are declared:
void f() { int i; i = 1; // OK: in scope } void g() { i = 2; // Error: not in scope }
Global variables (pedantically, variables with a file region (in C) or a namespace region (in C ++)) are available at any time after they are declared:
int i; void f() { i = 1;
(In C ++, the situation is more complicated, because namespaces can be closed and reopened, and areas other than the current one can be accessed, and names can also have a cool area, but this becomes very off topic.)
Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime expires when execution leaves the scope and is recreated when the region is re-entered.
for (int i = 0; i < 5; ++i) { int n = 0; printf("%d ", ++n);
Static variables (pedantically, variables with a static storage duration) have a lifespan that lasts until the end of the program. If they are local variables, then their value is preserved when the execution goes out of scope.
for (int i = 0; i < 5; ++i) { static int n = 0; printf("%d ", ++n);
Note that the static has different meanings besides static storage duration. According to a global variable or function, it gives an internal connection so that it is not accessible from other translation units; on a member of a C ++ class, this means that there is one instance for each class, not one object. Also, in C ++, the auto keyword no longer means automatic storage duration; now this means the automatic type deduced from the variable initializer.
Mike Seymour Nov 16 '12 at 11:26 2012-11-16 11:26
source share