C Reference ยท Keywords and Statements
The static keyword
Reference for the C static keyword: persistent local variables, internal linkage for globals and functions, and static in array parameters.
static has two unrelated main meanings depending on where it appears. On a local variable it gives the variable static storage duration: it is created once, keeps its value between calls, and lives until the program ends, while its name stays visible only inside the block. On a file-scope variable or function it gives internal linkage: the name is private to the current source file and cannot clash with the same name elsewhere.
A third, rarer use is in an array parameter, int a[static 4], which promises the caller passes at least four elements.
int next_id(void) { static int id = 0; /* initialized once */ return ++id; } static int helper(void); /* private to this file */
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
static type name = constant-initializer; /* block or file scope */ static return-type name(parameters); /* function with internal linkage */ type f(type a[static N]); /* parameter */
| Use | Meaning |
|---|---|
| Block-scope variable | Static storage duration, no linkage. Initializer must be a constant expression (C23 also allows constexpr objects). |
| File-scope variable or function | Internal linkage: visible only in this translation unit. |
a[static N] in a parameter |
The argument points to at least N accessible elements. |
Undefined behavior: passing fewer than N elements, or a null pointer, to a static N parameter.
Usage notes
- Initialization happens once, before
mainruns, and a missing initializer means zero (or null pointers). The initializer cannot call functions. - Not thread-safe: a static local shared by several threads is a data race unless protected or declared
thread_local. - Hidden state hurts testing. Functions like
strtokare awkward because of an internal static buffer; prefer passing state explicitly. - Returning a pointer to a static local is valid (unlike an automatic one) but every call shares the same object.
- Use
staticon helpers in.cfiles so they do not collide with other files and the compiler can inline or drop them. staticin a header gives each including file its own private copy; it is common for smallstatic inlinefunctions, see inline.- Compare with
extern, which asks for external linkage.