What is Storage in C?


storage class

Storage class represents the visibility and location of a variable. We have four different types of storage they are:- 

A) Automatic:-  auto variables are the local variable we don’t need to use keyword auto for this. Its initial value will be garbage. When the control comes inside the block it will be active otherwise it will destroy. 

Code  

#include <stdio.h>
void main() 


int a;  // auto  

auto int a;  // auto  

}  

 

B) Register:- they can be created as similar with local variables. When we make a register variable we will use a keyword register. The value of the variable will be store in the register in these cases. 

Code  


#include <stdio.h>
void main() 
register int a = 10

C) Static:-  we can use static variables with global as well as local variables. If we use know keyword static and define any local variable then its value will be there until the program won't finish, and as more, we call the function its value goes on increasing which is given in the example below.  



  1. For local variable  

    #include <stdio.h>
    void func1() 
    static int a = 10// local variable with static keyword  
    printf("%d", &a); 
    a++; //increment the value of a by 1/ 
    }  
    void main() 
    func1(); // calling func1 
    func1(); // calling func1 

    OUTPUT 

    1 

    2 

NOTE: the more we call the function the more value goes on increasing.  

 

  1. Global variable:- due to the use of static keyword we can't call this global variable in other files even with extern keyword but it will be global for only this file. let's see the example below,

    #include <stdio.h>
    static int a = 100
    void func1() 
    statement(1); 
    void main() 
    statement(2); 

     

 

D) External:- they are also called a global variable, they will be out from all functions. if there are two files ofc then we can call a function from one file to another. The initial value of the global variable will be zero(0). Let's see how can we use a global variable in a different file  

Code sample 

To use the global variable of one file to another we have to use the extern keyword 

File 1 

File 2 

#include <stdio.h>
int a = 100;
void main()
{
    statement(s);
    printf("%d"a);
}
#include <stdio.h>
extern int a;
void function2()
{
    statement(s);
    printf("%d", a);
}

 

Follow our page for regular updates.

0 Comments