US Trends

what is static variable in c

Quick Scoop: A static variable in C is a variable that keeps its value between function calls and exists for the entire program lifetime, instead of being destroyed when the function ends.

What it means

  • If you declare a variable as static inside a function, it is initialized only once and remembers its previous value on the next call.
  • If you declare a static variable at file scope, it is only visible within that source file, which helps limit access from other files.

Simple example

c

#include <stdio.h>

void counter() {
    static int count = 0;
    count++;
    printf("%d\n", count);
}

int main() {
    counter(); // 1
    counter(); // 2
    counter(); // 3
    return 0;
}

In this example, count does not reset every time counter() runs; it keeps its value across calls.

Key points

  • Lifetime: entire program run.
  • Scope: depends on where it is declared, function scope or file scope.
  • Default value: if not explicitly initialized, it is zero-initialized.
  • Common use: counters, state tracking, and preserving data between calls.

Static vs normal variable

Feature| Normal variable| Static variable
---|---|---
Lifetime| Only while the function/block runs| Entire program
Value between calls| Resets each call| Preserved
Default initialization| Not guaranteed| Zero if not initialized

If you want, I can also show the difference between local static , global static , and automatic variables with one clean code example.