Static variables in C

Static variables are declared with static keyword. Static variables have an essential property of preserving its value across various function calls. Unlike local variables, static variables are not allocated on C stack. Rather, they get their memory in data segment of the program.

Syntax to declare static variable

static data_type variable_name;

data_type is a valid C data type and variable_name is a valid C identifier.

Properties of a static variable

Static variables are widely known among C programmer due to its special properties which are –

  1. Static variables are allocated within data segment of the program instead of C stack.
  2. Memory for static variable is allocated once and remains throughout the program. A static variable persists, even after end of function or block.

    For example, consider the below function. It contains local and static variable. Let us demonstrate whether the value of static variable persists throughout the program or not.

    #include <stdio.h>
    
    /* Function declaration */
    void display();
    
    int main()
    {
        display();
        display();
        display();
    
        return 0;
    }
    
    /* Function definition */
    void display()
    {
        int n1 = 10;
        static int n2 = 10;
    
        printf("Local n1 = %d, Static n2 = %d\n", n1, n2);
    
        n1++; // Increment local variable 
        n2++; // Increment static variable
    }

    Output –

    Local n1 = 10, Static n2 = 10
    Local n1 = 10, Static n2 = 11
    Local n1 = 10, Static n2 = 12

    It is clear from the output that static variable persists throughout the program and preserves its value across various function calls.

  3. A static variable is initialized with a default value i.e. either 0 or NULL. For example –
    /**
     * C program to demonstrate static variable
     */
    #include <stdio.h>
    
    /* Function declaration */
    void display();
    
    int main()
    {
        display();
        display();
        return 0;
    }
    
    /* Function definition */
    void display()
    {
        int n1; /* Garbage value */
        static int n2; /* Default zero value */
        printf("Local n1 = %d, Static n2 = %d\n", n1, n2);
    }

    Output –

    Local n1 = 4200734, Static n2 = 0
    Local n1 = 4200734, Static n2 = 0
  4. You can access a global variable outside the program. However, you cannot access a global static variable outside the program.

When to use a static variable?

Static variable provides great flexibility to declare variable that persists its value between function calls. Use a static variable, if you need a variable whose value must persist between function calls.