In this tutorial, you will learn about C programming storage class: Auto, Static, Register and Extern.
In C programming, properties of variables include variable_name
, variable_type
, variable_size
and variable_value
.
We already know that variable in an identifier. Identifier has other properties such as storage class, storage duration, scope and linkage.
In C, there are four types of storage class:
Storage class of variable in C determines following things:
Local variables are declared within function body and have automatic storage duration.
For representing automatic storage duration keyword auto
is used.
Memory for the local variables is created when the function is invoked or active, and destroyed or de-allocated when a block is exited or control moves out of the function.
By default, local variables have automatic storage duration.
#include <stdio.h> int main () { int x; //local variable .... return 0; } int func_name () { int y; //local variable .... }
In the above program, both x
and y
are local variables but x
is only available to main
function whereas y
is only available to func_name
function.
[adsense1]
Register variables are stored in CPU registers and are available within the declared function.
The lifetime of register variable remains only when control is within the block.
Keyword register
is used to define register storage class. Register variables are accessed faster because it is stored in CPU register.
#include <stdio.h> int main() { register int x; //register variable for (x = 1; x <= 5; x++) { printf("\n%d", x); } }
Static variables are defined by keyword static
. For static variables, memory is allocated only once and storage duration remains until the program terminates.
#include <stdio.h> int main() { increment(); increment(); increment(); return 0; } void increment() { auto int x = 1; printf("%d\n", x); x = x + 1; }
#include <stdio.h> int main() { increment(); increment(); increment(); return 0; } void increment() { static int x = 1; printf("%d\n", x); x = x + 1; }
Explanation
In the above programs, increment()
function is called three times from the main
.
The only difference is the storage class of variable x.
Like auto
variables, static
variables are local to the function in which they are declared but the difference is that the storage duration of static
variables remains until the end of the program as mentioned earlier.
External variables are declared outside the body of the function. If they are declared in the global declaration section, it can be used by all the functions in the program.
#include <stdio.h> int x = 5; //global variable int main () { ...... ...... return 0; }
Note the difference in following
extern int x; int x = 5;
In the above example, the first statement is the declaration of the variable and the second statement is the definition.
Note: Automatic storage helps in preserving memory because they are created when the function is started and destroyed when the function is exited.