Automatic vs Static Variables

An introduction to automatic and static variables.

Two kinds of local variables

We talked about variable scope and the idea that variables declared within a function are local to that function. What actually happens is that each time a function is called by another piece of code, all the variables declared within the function are created (that is, memory is allocated to hold them). When the function is finished, all of that local memory storage is deallocated, and those variables essentially disappear. Such variables are known as automatic local variables (they are automatically created and then destroyed as the function is called, and then finishes).

If we want local variables to persist, we can declare them as static local variables. We simply insert the word static in front of the variable type when declaring it inside a function. When declared in this way, the variable will not be destroyed when the function exits, but it (and its value) will persist. Next time the function is called, the variable will have retained the value from the previous function call.

Example

Here’s an example program that maintains a running count of the number of times the function myFun() has been called in the variable num.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy