What are the three uses of the keyword static in C?
0 upvotes
Practice with AISoon
static has three distinct meanings depending on context:
- Inside a function — the variable retains its value between calls. It is allocated in
.bssor.data(not on the stack) and persists for the lifetime of the program. This is useful for counters, state machines, and cached values, but it makes the function non-reentrant — if called from two threads or from an ISR and main simultaneously, the shared static variable becomes a race condition. - At file scope (outside functions) — restricts visibility of the variable to the current translation unit (
.cfile). This is C's mechanism for creating "private" globals, preventing name collisions across files. - Applied to a function — restricts the function's linkage to the current translation unit, making it invisible to other files. This enables encapsulation in C, where there are no classes or namespaces.
Source: C / C++ Concepts Q&A
