ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-252 min read

Understand static vs global variables in C: file scope vs internal linkage, stack vs data segment memory, lifetimes, and storage classes.

Scope, Lifetime & Linkage Differences

Understanding variable storage classes is essential for writing robust C programs:

Variable TypeStorage LocationLifetimeScope / Linkage
Local (Auto)Stack MemoryFunction call durationBlock scope (Local only)
Static LocalData Segment (.data / .bss)Program lifetimeBlock scope (Retains value between calls)
Static GlobalData Segment (.data / .bss)Program lifetimeInternal linkage (Current translation unit only)
Global (Extern)Data Segment (.data / .bss)Program lifetimeExternal linkage (Accessible across files)

Complete Working C Code

c (ISO Standard)
#include <stdio.h>

/* Global variable: External linkage across entire program */
int globalCounter = 0;

/* Static global: Internal linkage restricted to this file */
static int filePrivateCounter = 100;

void demonstrateStaticLocal() {
    int autoVar = 0;       /* Reinitialized on every function call */
    static int staticVar = 0; /* Initialized ONCE; retains state */

    autoVar++;
    staticVar++;
    globalCounter++;
    filePrivateCounter++;

    printf("autoVar = %d | staticVar = %d | global = %d | staticGlobal = %d\n",
           autoVar, staticVar, globalCounter, filePrivateCounter);
}

int main() {
    printf("Executing function multiple times:\n\n");
    for (int i = 1; i <= 3; i++) {
        printf("--- Call #%d ---\n", i);
        demonstrateStaticLocal();
    }

    return 0;
}

Sample Output

text (ISO Standard)
Executing function multiple times:

--- Call #1 ---
autoVar = 1 | staticVar = 1 | global = 1 | staticGlobal = 101
--- Call #2 ---
autoVar = 1 | staticVar = 2 | global = 2 | staticGlobal = 102
--- Call #3 ---
autoVar = 1 | staticVar = 3 | global = 3 | staticGlobal = 103

Complexity Analysis

  • Time Complexity: O(1) direct variable access without stack reallocation.
  • Memory Allocation: Static and global variables persist in the process's data segment (.data / .bss).

Related C Examples & Tutorials