static Static storage duration and internal linkage
static Static storage duration and internal linkage
static gives locals static storage, initialized once. File-scope names get internal linkage; block static lacks linkage, adding no const or thread privacy.
| Category | Storage-class specifiers |
|---|---|
| Kind | Keyword / Statement |
| C standard | C89 / C90 |
📝 Syntax
static int counter = 0; /* Inside a function */
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
first = 1, second = 2
ℹ️ Info The example saves both return values before printing, avoiding evaluation-order issues within one printf call. The local count retains its value between calls.
🏷️ Related storage-class specifiers
📚 Related Tutorials
❓ FAQ
QHow many times is a local static variable initialized?
AAn object with static storage duration is initialized once during program startup and is not reinitialized on later function entries. Without an explicit initializer it is zero-initialized; its initializer must meet the rules for static objects.
QDo file-scope static and function-local static mean the same thing?
ANo. File-scope static primarily gives a name internal linkage, while function-local static extends storage duration until program termination. A block-scope static object itself still has no linkage.
QIs a static counter safe in a multithreaded program?
ANo. A local static is still shared by all threads. Concurrent non-atomic increments can cause a data race, so use atomic operations or mutual exclusion as appropriate.