Auto Storage Class in C (Keyword)

auto storage class

Auto Storage Class in C

Auto is default storage class for all variables declared inside a function or block. So, we rarely write auto   of any keyword in C.

Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope). These can be accessed within nested blocks within the parent block/function in which the auto variable was declared.

However, they can be accessed outside their scope as well using the concept of pointers given here by pointing to the very exact memory location where the variables resides. 

Auto storage class

  • 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. 
  • Auto storage class is default storage class.
 

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.
#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;
}

Output

3 2 1

Now we will write above code without using auto keyword

  • Without using auto keyword still the output of the program will be same.
  • 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.
#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;
}

Output

3 2 1