Storage Classes

Storage Classes

In a C programming, storage classes are used to define the storage area and visibility of a variable.

There are four types of storage classes in C:

  • auto - stored in stack area and can be accessed within the block where it is declared, whose initial value is garbage value.
    #include<stdio>
    int main(){
        auto int num1 = 10;
        auto int num2;
        printf("num1 = %d\n", num1);
        printf("num2 = %d\n", num2);
        return 0;
    }
    num1 = 10
    num2 = (garbage value)
  • extern - stored in data segment area and can be accessed throughout the program, whose initial value is zero. It is used to declare a global variable or function in another file. If you use extern keyword, the variable must be defined outside of the current file.
    variables.c
    extern int num1 = 10;
    extern int num2 = 20;

    main.c
    #include<stdio>
    #include "variables.c"
    int main(){
        printf("num1 = %d\n", num1);
        printf("num2 = %d\n", num2);
        return 0;
    }
    num1 = 10
    num2 = 20
  • static - stored in data segment area and can be accessed within the block where it is declared, whose initial value is zero. static variables retain their value between function calls.
    #include<stdio>
    int main(){
        static int i = 1;
        if(i<=3){
            printf("%d ", i);
            i++;
            main();
        }
        return 0;
    }
    1 2 3
  • register - stored in CPU register and can be accessed within the block where it is declared, whose initial value is garbage value. It is used to optimize the access speed of frequently used variables.
    #include<stdio>
    int main(){
        register int num1 = 10;
        register int num2;
        printf("num1 = %d\n", num1);
        printf("num2 = %d\n", num2);
        return 0;
    }
    num1 = 10
    num2 = (garbage value)

Common Interview Questions

  1. What is storage class?
  2. What are storage classes?
  3. Difference between auto and register storage class?
  4. What is meant by garbage value?