Storage Class in C
Storage Class in C
C Programming Language
Introduction
• Basically, computer allocates space for
variables in TWO ways
– Memory
– CPU Registers
Why Storage Classes?
• Where the variable would be stored?
– Memory or CPU Registers
• What will be the initial value of the variable?
– i.e., default value (Starting value)
• What is the scope of the variable?
– For which function the value of the variable would
be available
• What is the life time of a variable?
– How long would be variable exists
Types Storage Classes
• There are FOUR types of storage classes
– Automatic Storage class (auto)
– Register Storage class (register)
– Static Storage class (static)
– External Storage class (extern)
Automatic Storage Class
Storage Memory
Output: 20 10
Example 3
#include<stdio.h>
int main(){
{
int a=20;
printf("%d",a);
}
printf(" %d",a); //a is not visible here
return 0;
}
Output: 20 20 20 20
Register Storage Class
Storage Register
Storage Memory
Output: 0
Example 2
#include<stdio.h>
static int a;
int main(){
printf("%d",a);
return 0;
}
Output: 0
Example 3
#include <stdio.h>
static char c;
static int i;
static float f;
int main(){
printf("%d %d %f",c,i,f);
return 0;
}
Output: 0 0 0.000000
Example 4
#include <stdio.h>
static int i=10;
int main(){
i=25; //Assignment statement
printf("%d",i);
return 0;
}
Output: 25
Example 5
#include<stdio.h>
int main(){
{
static int a=5;
printf("%d",a);
}
//printf("%d",a); variable a is not visible here.
return 0;
}
Output: 5
External Storage Class
Storage Memory
Output: 0
Example 2
#include <stdio.h>
extern int i; //extern variable
int main(){
printf("%d",i);
return 0;
}
Output: 15
Example 4
#include <stdio.h>
extern int i=10; //extern variable
int main(){
printf("%d",i);
return 0;
}
Output: 10
Example 5
#include <stdio.h>
int main(){
extern int i=10; //Try to initialize extern variable locally.
printf("%d",i);
return 0;
}