Marking something as static within a function relocates its storage off of the stack and allows its value to persist across multiple calls.
Marking something static, however, does nothing to change the scope of the variable. While you certainly could create a pointer that is aimed at bar and manipulate it from main, the compiler will view bar as undefined within main because of scoping.
You are confusing the scope of a variable with the storage duration.
As mentioned in the C11 standard, chapter §6.2.1, Scopes of identifiers,
for file scope
[...] If the declarator or type specifier that declares the identifier
appears outside of any block or list of parameters, the identifier has file scope, which
terminates at the end of the translation unit. [...]
and for function (or block) scope
[...] If the declarator or type specifier that
declares the identifier appears inside a block or within the list of parameter declarations in
a function definition, the identifier has block scope, which terminates at the end of the
associated block. [...]
In your case, bar has the file scope in foo(). So this is not visible in main().
OTOH, for the storage duration part,
An object whose identifier is declared without the storage-class specifier
_Thread_local, and either with external or internal linkage or with the storage-class
specifier static, has static storage duration. Its lifetime is the entire execution of the
program and its stored value is initialized only once, prior to program startup.
So, to summarize, bar has static storage duration, but the scope is limited to the foo() function. So, it is
declared and initialized prior to main() function
(before main() starts, to be exact) but not visible and accessible in main().
Asked in February 2016Viewed 1,416 timesVoted 11Answered 2 times