C — Storage Classes

Prason Pandey
2 min readSep 27, 2020
Annette Sousa

Image for Attention!!!

When we create a variables, two things are always attached with variable their data type and storage class. Storage class decides the lifetime and scope or visibility of the variable in the program.

When we define a variable, it gets some physical area in memory where it’s value is stored. Memory and registers are two types of memory locations where a value of a variable can be stored. Storage class decides where a variable is going to stored i.e. either in memory or in registers.

Storage Class Types

We have four types of storage class.

Auto

Auto stands for automatic storage class. An automatic storage class is default class. When we declare a variable within a function without defining any storage class then variable automatically become auto storage class.

Any non static local variable is an auto variable and scope of the auto variable is inside the block. If the variable is not explicitly initialized, then it will hold an Garbage value. It is often good practice to initialize a local variable when it is declared. It gets destroyed on exit from the block. It is stored inside RAM.

int numbers(void)
{
int first; //auto variable
auto int second; //auto variable
}

Static

Static storage class can be used for local variables as well as global variables. Means we can use the term local static variable and global static variable.

Scope of the static variable is inside the file only in which it is declared and lifetime of the static variable is entire program. Static variables are by default initialized with zero and they are initialized only once in the program.

#include <stdio.h>void staticChecker()
{
static int n=0;
n++;
printf("%d \n",n);
}
int main()
{
int i;
for(i=0;i<10;i++)
staticChecker();
return 0;
}

Extern

Extern stands for external storage class. Extern storage class is used when we have global functions or variables which are shared between two or more files. The principle use of external storage class is to inform the compiler that the variable is declared somewhere else. The extern variables give us permission to access the variables between two different files which are the part of a large program.

Register:

Register variable stored in CPU register instead of memory and its properties is generally similar to the storage class auto. Accessing of the register is faster than the memory. So generally, the register variable is used in looping.

They can’t be accessed outside the code block and register variables will also be initialized with garbage value.

#include<stdio.h>main(){register int i;for(i=1; i<=100; i++)printf("n%d",i);return 0;}

Phew! Yeah, we’re finished. We completed learning basic of storage classes in C. This article is done, but you shouldn’t be done with pointers. Play with them. Increase your code's performance. Best Wishes.

Happy Coding!!! Happy Hacking!!!

--

--