`static` — C Keyword

`static` — C Keyword

The static keyword in C: controls storage duration and linkage.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

static (C)

Has two distinct uses: (1) static storage duration for local variables (they persist across calls), and (2) internal linkage for file-scope variables and functions (visible only within the translation unit).

Syntax

static Type local_var;           /* persists across function calls */
static Type file_var;            /* internal linkage at file scope */
static return-type func(params); /* internal linkage function */

Example

#include <stdio.h>

/* Internal linkage – not visible in other .c files */
static int call_count = 0;

static int increment(void) {
    ++call_count;
    return call_count;
}

int next_id(void) {
    static int id = 0;   /* initialized once; persists across calls */
    return ++id;
}

int main(void) {
    printf("%d\n", increment());  /* 1 */
    printf("%d\n", increment());  /* 2 */

    printf("%d\n", next_id());    /* 1 */
    printf("%d\n", next_id());    /* 2 */
    printf("%d\n", next_id());    /* 3 */
    return 0;
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}