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()
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:
static int 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…
In case you still have questions, we have a nice C tutorial here.