• Articles
  • Tutorials
  • Interview Questions

Storage Classes in C - The Complete Guide

Tutorial Playlist

The scope, lifetime, and initial value of variables are controlled by storage classes in C. Auto, Register, Static, and External are the four primary storage classes in C. The methods for creating, accessing, and destroying variables vary depending on the storage class.

What are the Storage Classes in C

It defines the scope, visibility and life time of variable. There are 4 types of storage classes in C:

  1. auto
  2. register
  3. extern
  4. static

1. auto

It is the default storage class for every local variables. When a function is called they are created and when the function exits they are destroyed automatically.
Example

void main(){
int data;
auto int data;    //Both are same
}

Master File Handling in C with our comprehensive tutorial!

2. register

It defines the local variables which are stored in register rather than RAM. Register variables have faster access than the normal variable.

Example

register int data;

Certification in Full Stack Web Development

Learn the basics of Loops in C through this blog!

3. extern

It gives the reference of a global variable which is visible to all program files. It keyword is used before a variable to tell the compiler that this variable is declared somewhere else. The extern declaration does not allocate storage for variables.
Example 1
Suppose there are two files a and b.

File a contains:

#include <stdio.h>
int i=10;  / /Global variable
void display()
{
printf(“%d”, i);
}

File b contains:

#include<stdio.h>
#include a.c
void main()
{
extern int i;
display();
getch();
}

Example 2

#include<stdio.h>
int i;    //Global variable
void main(){
extern int i;  //Informs compiler that it is defined somewhere else  i = 20;
printf("%d",i);
}

Get the most out of C and become a better developer through this C Tutorial!

4. static

It tells the compiler to keep a local variable in existence during the life time of the program rather than creating and destroying it every time it comes into and goes out of scope. So making local variables static permits them to keep their values between function calls. They are assigned 0 as default value by the compiler. 
Example

#include<stdio.h>
void dispaly();
void main(){
display ();
display ();
}
void display()
{
static int i = 0;  //Static variable
i = i + 1;
printf("%d\n",i);
}

Output
12

If you want to know about Array in C, refer to our C programs blog!

Course Schedule

Name Date Details
Python Course 20 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 27 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 04 May 2024(Sat-Sun) Weekend Batch
View Details

Full-Stack-ad.jpg