This blog is under construction

Sunday, 13 May 2012

Automatic storage class in C

Auto Variables:
"auto" is the default storage class for the variables without any storage class.  Auto variables are active within the block in which they are declared.  They are defined with in functions.  Memory for these variables are allocated during the time of declaration and they will get destroyed once program execution for that block gets over.

Auto variable example:
int func() {
       auto int val;  //val is an auto variable
       ..........
       return 0;
}


Example C program using auto variables
 
  #include <stdio.h>
  int main() {
        auto int num = 100;  // auto variable
        printf("Outside inner block - value of "
                        "num before inner block: %d\n", num);
        {
           printf("Inside inner block - value of "
                        "num before declaration: %d\n", num);
           auto int num = 20;  // auto variable
           printf("Inside inner block - value of "
                        "num after declaration: %d\n", num);
        }
        printf("Outside inner block - value of "
                        "num after inner block: %d\n", num);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Outside inner block - value of num before inner block: 100
  Inside inner block - value of num before declaration: 100
  Inside inner block - value of num after declaration: 20
  Outside inner block - value of num after inner block: 100



No comments:

Post a Comment