The storage classes specify the scope and lifetime of a variable in a C program. The scope (active) specifies in which parts of the program is the variable accessible and the lifetime (alive) specifies how long a variable is available in the memory so that the program will be able to access that variable. There are four storage classes in C. They are:
The storage classes’ auto, register and static can be applied to local variables and the storage classes’ extern and static can be applied to global variables.
When a variable is declared with the storage class auto, the variable’s scope is within the function or block in which it is declared and the lifetime is until the function or block in which it is declared completes. Syntax for declaring auto variable is shown below:
In any program, if a local variable is declared without any storage class then it is automatically set to auto storage class.
When a variable is declared with the storage class register, the variable will be stored inside one of the registers of the CPU. The registers are under the direct control of CPU. So, data inside the register can be processed at a faster rate than the data that resides in the main memory. For a program to execute faster, it is always best to store the most frequently used data inside register. The scope and lifetime of a register variable is same as that of a auto variable. Syntax for declaring a register variable is as shown below:
The extern storage class specifies that the variable is declared in some part of the program. Generally this storage class is used to refer global variables in a program. Note that extern variables cannot be initialized. The scope of a extern variable is throughout the entire program and the lifetime is until the program completes its execution.
In a multi-file program, a global variable in one file can be accessed from another file by using the storage class extern. Syntax for declaring a extern variable is as shown below:
The static storage class can be applied to both local variables and global variables. The static local variables are accessible only within the function or block in which they are declared, but their lifetime is throughout the program. The static global variables are accessible throughout the file in which they are declared but not in other files. Syntax for declaring static variable is shown below:
The four storage classes can be summarized as shown below:
Note: The extern variables cannot be initialized. The default value for static variables is zero.