According to https://www.learn-c.org/en/Static:
By default, variables are local to the scope in which they are defined. Variables can be declared as static to increase their scope up to file containing them. As a result, these variables can be accessed anywhere inside a file.
Two code examples are provided.
First, an example where local variable int count is removed from memory after the function runner() returns:
#include<stdio.h>
int runner() {
int count = 0;
count++;
return count;
}
int main()
{
printf("%d ", runner());
printf("%d ", runner());
return 0;
}
The output is: 1 1.
The next example given makes count static:
#include<stdio.h>
int runner()
{
static int count = 0;
count++;
return count;
}
int main()
{
printf("%d ", runner());
printf("%d ", runner());
return 0;
}
The output this time is: 1 2.
count increased to 2 in this example because it wasn't removed from memory at the return of runner().
...BUT, that doesn't seem to relate to the statement at the beginning of the page about static variables being accessed anywhere inside a file. The two examples only show that static allowed count to remain in memory across multiple calls to runner() (and that it is not set to 0 each call). They do not show whether or not count can be accessed "anywhere inside a file", because main() simply prints whatever runner() returns.
To illustrate my point, I made an example showing that static does not make count() accessible anywhere inside a file:
#include<stdio.h>
void runner()
{
static int count = 0;
count++;
return;
}
int main()
{
runner();
printf("%d ", count);
runner();
printf("%d ", count);
return 0;
}
The output is:
prog.c: In function 'main':
prog.c:12:23: error: 'count' undeclared (first use in this function)
printf("%d ", count);
^
prog.c:12:23: note: each undeclared identifier is reported only once for each function it appears in
That is what I expected.
I made another example, this one uses x which can be accessed by both runner() and main():
#include<stdio.h>
int x = 0;
void runner()
{
static int count = 0;
count++;
x = count;
return;
}
int main()
{
runner();
printf("%d ", x);
runner();
printf("%d ", x);
return 0;
}
The output is: 1 2.
Is the quote at the top of this question incorrect, misleading, or neither? Am I misunderstanding a semantics issue?