Problem
What are different storage classes in C Language? Explain them with programs?
Solution
A storage class is defined as the scope and life-time of variables or a functions that is present within a C Program.
Storage classes
Following are the storage classes in C −
- auto
- extern
- static
- register
Automatic variables/Local variables
- Keyword − auto
- These are also called local variables
- Scope −
Scope of a local variable is available within the block in which they are declared.
These variables are declared inside a block
- Default value − garbage value
Example
#include<stdio.h>
void main (){
auto int i=1;{
auto int i=2;{
auto int i=3;
printf ("%d",i);
}
printf("%d", i);
}
printf("%d", i);
}Output
3 2 1
Global Variables/External variables
- Keyword − extern
These variables are declared outside the block and so they are also called global variables
Scope − Scope of a global variable is available throughout the program.
- Default value − zero
Example
#include<stdio.h>
extern int i =1; /* this ‘i’ is available throughout program */
main (){
int i = 3; /* this ‘i' available only in main */
printf ("%d", i);
fun ();
}
fun (){
printf ("%d", i);
}Output
31
Static variables
- Keyword − static
- Scope − Scope of a static variable is that it retains its value throughout the program and in between function calls.
- Static variables are initialized only once.
- Default value − zero
Example
#include<stdio.h>
main (){
inc ();
inc ();
inc ();
}
inc (){
static int i =1;
printf ("%d", i);
i++;
}Output
1 2 3
Register variables
- Keyword − register
Register variable values are stored in CPU registers rather than in memory where normal variables are stored.
Registers are temporary storage units in CPU.
Example
#include<stdio.h>
main (){
register int i;
for (i=1; i< =5; i++)
printf ("%d",i);
}Output
1 2 3 4 5