c - Why doesn't `bar` in this code have static storage duration? -
code goes first:
#include <stdio.h> void foo() { static int bar; } int main() { bar++; return 0; }
the compiler(clang) complains:
static.c:10:2: error: use of undeclared identifier 'bar'
shouldn't statement static int bar;
in foo()
give bar
static storage duration, makes declared , initialized prior main function?
you confusing scope of variable storage duration.
as mentioned in c11
standard, chapter §6.2.1, scopes of identifiers,
- for file scope
[...] if declarator or type specifier declares identifier appears outside of block or list of parameters, identifier has file scope, terminates @ end of translation unit. [...]
and function (or block) scope
[...] if declarator or type specifier declares identifier appears inside block or within list of parameter declarations in function definition, identifier has block scope, terminates @ end of associated block. [...]
in case, bar
has file scope in foo()
. not visible in main()
.
otoh, storage duration part,
an object identifier declared without storage-class specifier
_thread_local
, , either external or internal linkage or storage-class specifierstatic
, has static storage duration. lifetime entire execution of program , stored value initialized once, prior program startup.
so, summarize, bar
has static storage duration, scope limited foo()
function. so, is
declared , initialized prior
main()
function
(before main()
starts, exact) not visible , accessible in main()
.
Comments
Post a Comment