0
0
Cprogramming~5 mins

Static storage class

Choose your learning style9 modes available
Introduction

The static storage class in C helps keep a variable or function's value or state between uses, and controls its visibility in the program.

When you want a variable inside a function to remember its value between calls.
When you want to limit a variable or function to be used only within one file.
When you want to avoid reinitializing a variable every time a function runs.
When you want to hide helper functions or variables from other parts of the program.
When you want to keep track of counts or states inside a function without using global variables.
Syntax
C
static data_type variable_name = initial_value;

The static keyword can be used with variables inside functions or outside functions.

Static variables inside functions keep their value between calls but are only visible inside that function.

Examples
This function uses a static variable to remember how many times it was called.
C
void count_calls() {
    static int count = 0;
    count++;
    printf("Called %d times\n", count);
}
This variable is only visible inside this file, not outside.
C
static int file_var = 10;

void print_var() {
    printf("Value: %d\n", file_var);
}
Sample Program

This program shows how a static variable inside a function keeps its value between calls.

C
#include <stdio.h>

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

int main() {
    demo_static();
    demo_static();
    demo_static();
    return 0;
}
OutputSuccess
Important Notes

Static variables are initialized only once, when the program starts or when the function is first called.

Static variables inside functions are not destroyed when the function ends.

Using static for global variables or functions limits their scope to the file, helping avoid name conflicts.

Summary

Static keeps variables alive between function calls.

Static limits variable or function visibility to the file or function.

Use static to remember values or hide details inside a file.