C – Storage Classes

Introduction:

  • We need to specify the storage class along with datatype in variable declaration.
  • Storage class describes
    • Memory location of variable
    • Default value of variable
    • Scope of variable
    • Lifetime of variable
  • Storage classes classified into
    • Automatic Storage classes
    • Register Storage classes
    • Static Storage classes
    • External Storage classes
Syntax:
            storage_class  datatype  name ;
Example:
            auto int a ;
            static int b ;

Block scope of a variable:

  • Defining a variable inside the block.
  • We can access that variable from the same block only.
  • We cannot access from outside of the block or from other block.
#include<stdio.h>
int main()
{
            {
                        int a=10;
                        printf(“a val : %d \n”, a);          
            }
           
           
            {
                        int b=20;
                        printf(“b val : %d \n”, b);
                        printf(“a val : %d \n”, a);             // Error :
            }
            return 0;
}

Function scope of a variable:

  • Defining a variable inside the function.
  • We can have number of blocks inside the function.
  • Function scope variable can access throughout the function and from all block belongs to that function.
#include<stdio.h>
int main()
{
            int a=10;  /* function scope */
           
            {
                        int a=20; /* block scope */
                        printf(“Inside First block, a val : %d \n”, a);     
            }
           
           
            {
                        printf(“Inside Second block, a val : %d \n”, a);
            }
           
            printf(“Inside function, a val : %d \n”, a);        
            return 0;
}

Note: If we don’t provide any value to local variable, by default the value is “Garbage value”

#include<stdio.h>
int main()
{
            int a;   
            {
                        int a=10;
                        printf(“a val : %d \n”, a);          
            }
           
            {
                        printf(“a val : %d \n”, a);          
            }
           
            return 0;
}

Program scope:

  • Defining a variable outside to all function
  • We can also call it as Global variable
  • We can access the global variable throughout the program.
#include<stdio.h>
void test(void);
int a=10; /*program scope*/
int main()
{
            int a=20; /*function scope */  
            {
                        int a=30; /*block scope */
                        printf(“In block : %d \n”, a);    
            }
            printf(“In main : %d \n”, a);     
            test();
            return 0;
}
void test()
{
            printf(“In test : %d \n”, a);       
}
Scroll to Top