Storage Classes in C

A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. These specifiers precede the type that they modify. It is worth mentioning here that the following text should be read again in the context of functions discussed in lesson 13 to better understand it. There are following storage classes which can be used in a C program:

The auto storage class is the default storage class for all local variables. The keyword used to specify a variable as as auto storage class is auto.

int w;
auto int w;

The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.

The register storage class is used to define local variables that should be stored in a register instead of RAM. The keyword used to specify a variable as within register storage class is register. This means that the variable has a maximum size equal to the register size (usually one word). The register should only be used for variables that require quick access such as counters. It should also be noted that defining register does not guarantee that the variable will be stored in a register. It will be stored in a register depending on hardware and implementation restrictions.

The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The keyword used to specify a variable as within static storage class is static. The static modifier may also be applied to global variables. When this is done, it causes that variable’s scope to be restricted to the file in which it is declared.

The extern storage class is used to give a reference of a global variable that is visible to all the program files. The keyword used to specify a variable as within extern storage class is extern. When you use extern the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined. When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions.