Storage classes in C helps us to define the scope and lifetime of the variables/functions. There are four different types of Storage classes in C:

  1. auto (automatic)
  2. static
  3. register
  4. extern

Storage-classes-in-C

1. auto or (automatic) storage class

The auto or automatic storage class is the default storage class for all the local variables in C language. The auto keyword is optional for this storage class.

Program example of auto storage class

#include<stdio.h>

int main()
{
    int x = 10; //without auto keyword
    
    auto int y = 20;

    printf("Value of x is: %d\n",x);
    printf("Value of y is: %d\n",y);
    return 0;
}

Output

Value of x is: 10
Value of y is: 20

2. static storage class

In the static storage class the memory allocated to the variable remains static throughout the program execution and deallocates on the end of the program. The lifetime of this storage class is till the end of the program. The static keyword is used to define this storage class.

Program example of static storage class

#include<stdio.h>

void change()
{
    static int x = 1;
    auto int y = 1;

    x++;
    y++;

    printf("static variable after increment is %d\n", x);
    printf("auto variable after increment is %d\n", y);
}
int main()
{
    change();
    change();
    return 0;
}

output

static variable after increment is 2
auto variable after increment is 2
static variable after increment is 3
auto variable after increment is 2

3. register storage class

Register variables are stored into the CPU registers. Since the registers are very close to the CPU so accessing the value from the CPU register is very fast. The lifetime of this storage class is only within the block. The keyword register is used to declare this storage class variables.

Program example of register storage class.

#include<stdio.h>

int main()
{
    register int x = 10;

    printf("value of x is %d\n", x);
    return 0;
}

4. extern storage class

The extern storage class is declared outside all the functions. The keyword extern is used to declare the extern storage class. The scope of the extern storage class variable is global and can be accessed anywhere within the program if it is declared in the global declaration section. The extern variables can also be accessed to multiple files.

Program of extern storage class

//In q.c file
int x = 10;


//In p.c file
#include<stdio.h>
#include"q.c"

int main()
{
    extern int x;

    printf("Value of extern variable x is %d\n", x);
    return 0;
}

Output

Value of extern variable x is 30