Recently, a professor for IT at the school I attend approached me with a broken program of his. The bug was connected to the keyword ‘static’.
Static is a ‘two headed’ hydra. It can be used in two ways which are not interlinked at all:
Global variable/Function static
In C, every variable that is not in a function is globally accessible from every other file. The same thing is valid for functions.
static int foo()
{
code
}
The function given above is ONLY visible in the file that contains it physically. Unlike a regular function, one cannot access it from other files.
//file begins here
static int foo;
//functions begin here
The code segment above defines a file global variable. This means that is can be acessed from every function, but only from those that are in the same file.
Function variable static
Using static as a memory class for a local variable in a function behaves entirely different:
void foo()
{
static int bar;
bar++;
}
In this code, the value of the variable survives multiple invocations of the function foo. So, bar will increase by one each time the function foo is called. C’s regular variable clearing is disabled for each local variable defined static…
Any comments?
In case you still have questions, we have a nice C tutorial here.
Related posts:

In the case of
void foo()
{
static int bar;
bar++;
}
bar becomes actually a global variable. Just the visibility is limited to the block in which it is declared. That bar is a gloabl variable has to be in mind, whenever you work with non-standard launch codes, like responses to global find, exchange manager etc.
Regards
Henk
Hi Henk,
thank you so much for the comment!
Best regards
Tam Hanna