What Is Storage Classes In C?
Storage classes decides the scope of variables (local or global), storage(in register or RAM) where it will be stored, default value(zero or Garbage) and their lifetime (in a bock where it is declared).
Storage Classes Keywords, Scope, Storage, And Lifetime.
Storage Classes keyword | Scope | Storage | Default Value | Lifetime |
---|---|---|---|---|
auto | Local | RAM | Garbage Value | In a block where it is declared |
register | Local | Register | Garbage Value | Within the function |
static | Local | RAM | Zero | Till the end of the main program |
extern | Global | RAM | Zero | Till the end of the main program |
Automatic Storage Classes
auto
keyword is used to define automatic storage class for variables. automatic storage class is default for all variables, don't need to do that.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int a; // auto storage class
// auto int a; same as above
printf("The value of %d\n",a); // default value is garbage
return 0;
}
Register Storage Class
register
keyword is used to define a variable in CPU register instead of RAM. It's default value is garbage. Frequenlty used variables may be define as register storage class. register keyword is maily used for char and int data type only.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
register int a; // register storage class
printf("The value of %d\n",a); // default value is garbage
return 0;
}
Static Storage Class
static
keyword is used to create a variable static storage class that is alive whole life of main program and it's default value is zero.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
static int a; // static storage class
a = 10;
printf("The value of %d\n", a); // default value is 0
return 0;
}
External Storage Class
external
keyword is used to access external storage class's variables in a function or a block. when we declare a variables outside of main function that will be a external storage class. It's scope is global.
#include <stdio.h>
#include <stdlib.h>
int number = 50; //global variable
int main(int argc, char const *argv[])
{
int number = 34;
{
extern int number; // access external storage class variable
printf("The value number inside a block is %d \n", number); // global variable
}
printf("The value of number is %d \n", number); // local variable
return 0;
}