35

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?

Community
  • 1
  • 1
Sency
  • 2,818
  • 8
  • 42
  • 59
  • I did, but difficult to understand the exact purpose. I could understand little about using with variables. but use with function ? – Sency Jan 02 '11 at 01:06
  • 1
    did you find this: http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program – Mitch Wheat Jan 02 '11 at 01:07
  • 1
    ...or this: http://stackoverflow.com/questions/943280/difference-between-static-in-c-and-static-in-c – Mitch Wheat Jan 02 '11 at 01:08

2 Answers2

60

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 to 0 by default.

Simon Gibbons
  • 6,969
  • 1
  • 21
  • 34
Roux hass
  • 754
  • 5
  • 5
  • 8
    Regarding 1: static can also be applied to functions, also concealing them to the outside. – datenwolf Jan 02 '11 at 22:19
  • 7
    Its been said in other incarnations of this question but for those coming from Google, strictly speaking 1 applies to compilation units not files. – Jared Nov 09 '13 at 06:36
  • @Roux hass: "If they are defined initialized" What does that mean? If they are initialized with a non-zero value upon being defined? –  Dec 04 '15 at 07:20
34

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 of static 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).

datenwolf
  • 159,371
  • 13
  • 185
  • 298