Storage Classes in C

Blog Contents

Storage Classes in C

To describe the features of the variable we use storage classes in c programming. Storage classes are used to track the variable during the run time of the program. Storage class describes the lifetime, scope of the variable in a program.
There are four storage classes in c program. They are auto, register, static and extern.
Storage classes in C

Auto:

The variable normally declared inside block or function is of auto type i.e auto is a default storage class for all the variables which are declared inside the block or function.
The scope of auto variables are within the block or functions means Auto variables can be only accessed within the block/function they have been declared and not outside them.
{
Int a;
auto int a;
}
Above we declared two variable of the same type.

Register:

The register storage class is used to define local variables that should be stored in a register instead of RAM.
{
register int c;
}
The register should only be used for variables that require quick access such as counters. It should be noted that describing ‘register’ it does not mean that the variable will be stored in a register. It means it might be stored in a register depending on hardware and implementation restrictions.

Static Variable

The static storage class notifies the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.
The static variable can be external or internal, its depends on the place of declaration.
#include<stdio.h>
void foo();
int main(void)
{
foo();
foo();
foo();
}
Void foo()
{
Static int x=1;
Printf(“x=%d”,)
x=x+1;
}

Output: 1,2,3.

Extern

The keyword extern is used with a variable to notify the compiler that the declaration of a variable is done somewhere else. The declaration of extern does not allocate storage for variables.
File1.c //
#include<stdio.h>
int x=3; //global declaration of variable
void foo()
{
 x++;
printf(“%d”,x);
}
File2.c
#include”file1.c”                   //including the file1
main()
{
Extern int x; // global variable from file1 is extracted so x=3.
Foo();
}
So the global variable which is declared in one file can be used in other file using the extern.