The specifiers which determines storage classes in C are called as Storage Class Specifiers, which are categorized into 4 types.
Conceptual
figure
Automatic Storage Class
Description
The variables declared inside a block without any storage class specification can be considered as automatic storage class.
These variables are also called as local variables as they get destroyed after the execution of the block.
As the variables are created automatically, garbage values are assigned by the compiler.
Example
Register Storage Class
Description
The variables stored in register storage class are similar to automatic storage classes in C.
Scope of the variable is same as automatic class.
Register variables are stored in CPU registers in order to retrieve the values faster.
Provides space for only few variables as the register size is very low.
The default value is the garbage value(could be anything).
Examples
[c]#include<stdio.h>
void main()
{
register int i = 1;
int *p = &i; //error : address cannot be retreived.
printf("Value of i: %d", *p);
printf("Address of i: %u", p);
}[/c]
Extern Storage class
Description
The variables declared with "extern" keyword states that the value possessed by that variable is already in use.
Extern variables are also called as global variables, because if the value is specified in one file, it can be accessed by other files also. No storage space is allotted to these variables.
Default value of any external variable is '0' (zero).
Example
In the below example, the value 75 is declared with a keyword extern which can be used by other functions like display().
[c]
#include<stdio.h>
int num = 75 ; //extern variable
void display();
void main()
{
extern int num ;
printf("\nNum : %d",num);
display();
}
void display()
{
extern int num ;
printf("\nNum : %d",num);
}[/c]
Output:
[c]
Enter the Number 1 : 5
Enter the Number 2 : 10
Sum of Numbers : 15
[/c]
Static Storage class
Description
Static Storage classes in C consists of variables which can retain its value depending on the function call.
The scope of the variable will not be effected i.e. variable remains local to the block in which it lies.
Example
In the below example, irrespective of the scope, the value got incremented depending on the function call.
[c]
#include<stdio.h>
void increment();
void main()
{
increment();
increment();
increment();
}
void increment()
{
static int a = 0;//Static variable
a = a+1;
printf("%d\t",a);
}
[/c]
Output:
[c]
1 2 3
[/c]
Summary
Key Points
Storage class decides scope, visibility and life-time of a variable.
auto storage class variables are deleted after execution.
register variables stores only some values.
extern variables are operated and declared outside the program.
static variables value can be changed as per the function call.
Programming
Tips
Note:
Getting the address of register variables is very difficult.