#include <stdio.h>
static i = 5;
int main()
{
extern int i;
printf("%d\n",i);
return 0;
}
Can someone give any use-case for declaring a static variable as extern inside a function block?
NEW:
Why is this not allowed?
int main()
{
static i = 5;
extern int i;
printf("%d\n",i);
return 0;
}
this is useful when you need to access a variable that resides within another translation unit, without exposing the external variable globally (for a few reasons, like name collision, or that the the variable shouldn’t be directly accessed, so
staticwas used to limit its scope, but that TU’s header still needs access).As an example, lets say we have a translation unit
foo.c, it contains:ishouldn’t be changed or directly accessed outsidefoo.c, however,foo.hcomes along requiring access toifor an inline function, butishouldn’t be exposed to any translation unit usingfoo.h, so we can useexternat functional level, to expose it only during the scope ofIncI, the inline function requiring the use ofi:Your second example is ‘disallowed’ because the compiler thinks you are trying to bind two different variables to the same symbol name, ie: it creates the
static iat local scope, but searches for theextern int iat global scope, but doesn’t find it, becausestatic ias at the function scope. a more clever compiler would just fix the linkage to thestatic i, whether or not this follows standards I wouldn’t know.Now that I have a C standards document to work from (shame on me I know…), we can see what the official stance is (in C99):
thus, because
staticwill cause internal linkage, theexternwill bring that linkage into the current scope. there is also a footnote stating that this may cause hiding of variables: