Auto Storage Class in C (Keyword)

auto storage class

Auto Storage Class in C

  • A variable defined within a function or block with auto specifier belongs to automatic storage class.
  • All variables defined within a function or block by default belongs to automatic storage class if no storage class is mentioned.
  • Variables having automatic storage class are local to the block in which they are defined.
  • Variables get destroyed on exit from the block, in which they are defined.
  • Default values of the variables of automatic storage class is by default any garbage value. 

Working of the Code 

  • In this code auto int i is defined at different stages with different scopes.
  • Each time auto int i is defined, it’s value will be printed only in that particular scope only.
  • First of all auto int i = 3 will be printed, then it’s scope will end.
  • Then auto int i = 2 will be printed, and then it’s scope will end.
  • At the end auto int i = 1 will be printed.

Output

3    2    1
#include <stdio.h>
int main()
{
    auto int i = 1;
    {
        auto int i = 2;
        {
            auto int i = 3;
            {
                printf("%d ",i);
            }
        }
        printf("%d ",i);
    }
    printf("%d ",i);
    return 0;
}

auto storage class is default storage class. 

  • auto storage class is default storage class.
  • In this example if we run above program without auto keyword even then it will show same output.
  • first of all int i = 3 will be printed.
  • then int i = 2 will be printed.
  • at the end int i = 1 will be printed.

Output

3    2    1
#include <stdio.h>
int main()
{
    int i = 1;
    {
        int i = 2;
        {
            int i = 3;
            {
                printf("%d ",i);
            }
        }
        printf("%d ",i);
    }
    printf("%d ",i);
    return 0;
}