main x: 10 inner x: 100 outer x: 0 main x: 11 inner x: 101 outer x: 0 main x: 12 inner x: 102 outer x: 0 main x: 13 inner x: 103 outer x: 0 main x: 14 inner x: 104 outer x: 0
Comments:
There are four variables x
in this file:
x
at the top of the file. This x
has file scope
(is visible anywhere in the file unless another x
hides it).
It is implemented in static memory, so its values persist.
The linker does not see it, so x
's in other files are different.
This x
is not actually used anywhere in this program.
x
declared inside the body of foo()
.
This x
has block scope (is only visible inside its block, except
where hidden by an x
in an inner block), no linkage, and
automatic storage. It is re-created on the stack
and re-initialized to zero each time foo()
is entered.
x
declared in a block nested inside the
body of foo()
.
This x
has block scope (is only visible inside its block), no linkage, and
static storage.
It hides the other local variable x
, so the
printf()
in that block refers to this x
.
Since it is implemented in static
memory, its values persist between
function calls.
x
declared in the
body of main()
.
This x
has block scope, no linkage, and
automatic (stack) storage.
Control remains in main()
for the entire run of
the program (although main()
is suspended when it calls a function),
so x
continues to exist throughout the run and retains its values.
#include <stdio.h> static int x = 44; /* x number 1: file scope, internal linkage, static memory */ foo() { int j = 0, x = 0; /* x number 2: block scope, no linkage, automatic (on the stack) */ { static int x = 100; /* x number 3: block scope, no linkage, static memory */ printf(" inner x: %d\n", x ); /* use x number 3 */ x++ ; /* use x number 3 */ } printf(" outer x: %d\n", x ); /* use x number 2 */ } main() { int x; /* x number 4: block scope, no linkage, automatic (on the stack) */ for ( x=10; x<15; x++ ) /* use x number 4 */ { printf("main x: %d\n", x ); /* use x number 4 */ foo(); } system("pause"); }