Skip to main content
Engineering LibreTexts

3.5: Static local variables

  • Page ID
    40722
  • Local variables on the stack are sometimes called automatic, because they are allocated automatically when a function is called, and freed automatically when the function returns.

    In C there is another kind of local variable, called static, which is allocated in the global segment. It is initialized when the program starts and keeps its value from one function call to the next.

    For example, the following function keeps track of how many times it has been called.

    int times_called()
    {
        static int counter = 0;
        counter++;
        return counter;
    }
    

    The keyword static indicates that counter is a static local variable. The initialization happens only once, when the program starts.

    If you add this function to aspace.c you can confirm that counter is allocated in the global segment along with global variables, not in the stack.

    • Was this article helpful?