Possible Duplicate:
What does “static” mean in a C program?
What does the static
keyword mean in C ?
I'm using ANSI-C. I've seen in several code examples, they use the static
keyword in front of variables and in front of functions. What is the purpose in case of using with a variable? And what is the purpose in case of using with a function?
static
within the body of a function, i.e. used as a variable storage classifier makes that variable to retain it's value between function calls – one could well say, that a static variable within a function is global variable visible only to that function. This use ofstatic
always makes the function it is used in thread unsafe you should avoid it.The other use case is using
static
on the global scope, i.e. for global variables and functions: static functions and global variable are local to the compile unit, i.e. they don't show up in the export table of the compiled binary object. They thus don't pollute the namespace. Declaring static all the functions and global variables not to be accessible from outside the compile unit (i.e. C file) in question is a good idea! Just be aware that static variables must not be placed in header files (except i very rare special cases).Just as a brief answer, there are two usages for the
static
keyword when defining variables:1- Variables defined in the file scope with
static
keyword, i.e. defined outside functions will be visible only within that file. Any attempt to access them from other files will result in unresolved symbol at link time.2- Variables defined as
static
inside a block within a function will persist or "survive" across different invocations of the same code block. If they are defined initialized, then they are initialized only once.static
variables are usually guaranteed to be initialized to0
by default.