Storage Class

The storage class of a variable determines its lifetime or when it is available. There are two storage classes: static and auto (i.e. automatic).

A data object that has static storage class exists and retains its value throughout the execution of the program. Even if it is a local variable to one function, that value continues even after returning from the function, and is not changed upon (re)entry into the function unless explicitly changed (e.g. if it is explicitly assigned a value). If the static local variable is initialized, that only happens once when the program is loaded.

A new instance of a data object that has automatic storage class is created on each entry into the block in which it is declared or on a jump into the block or an enclosed block. It is discarded when execution of the block ends by reaching the terminating }, by jumping to an enclosing block, or by executing a return statement.

Thus for a recursive function with automatic variables, each concurrently called instance of the function has its own private copy of the automatic variables.

Data objects defined outside of a function are always static. All data objects defined within a function are of automatic storage class unless explicitly declared with the static keyword modifier.

Automatic variables are conceptually kept on the stack (unless the compiler puts them in a hardware register for speed). Do not confuse storage class with scope as they are very different. Storage class is about values and when they are retained, while scope is about names and where they can be used in a source program.


© 1991-2008 Prem Sobel. All Rights Reserved.