Storage Class in C
C programming and its types. A storage class represents the visibility and the location of a variable. It tells from which part of code we can access a variable.
A storage class is used to describe the following things:
- The variable scope.
- The location where the variable will be stored.
- The initialized value of a variable.
- A lifetime of a variable.
- Who can access a variable?
A storage class is used to represent the information about a variable.
How many storage classes defined in C Programming Language?
There are 4 storage classes defined in C programming languages, that are defined below.
Storage Class |
Declaration |
Storage |
Default Initial Value |
Scope |
Lifetime |
auto |
Inside a function/block |
Memory |
Unpredictable |
Within the function/block |
Within the function/block |
register |
Inside a function/block |
CPU Registers |
Garbage |
Within the function/block |
Within the function/block |
extern |
Outside all functions |
Memory |
Zero |
Entire the file and other files where the variable is declared as extern |
program runtime |
Static (local) |
Inside a function/block |
Memory |
Zero |
Within the function/block |
program runtime |
Static (global) |
Outside all functions |
Memory |
Zero |
Global |
program runtime |
1. static
A static variable is visible only inside their own function and it can retain its values during the function calls and can be declared by adding static keyword before data type.
static data_type variable_name;
2.auto
An automatic variable is a variable which is declared inside a block also known as function and by default, all the variables are automatic variable and a variable can be defined as an auto variable by adding the prefix keyword auto in it.
auto data_type variable_name;
3.register
In order to store the value of the variable in a register, we have to add a keyword “register” before the variable name and it helps in reducing the time for performing any operations on register variable. Visibility of a register variable is only within a block(function).
register data_type variable_name;
Note : Declaring a variable doesn’t ensure that the variable will be stored in the registered it is just a request to a compiler to store that variable in register whereas it depends on register whether it saves the variable in register or not
4.extern
In C programming language external variables can be used across multiple files. Storage for an extern variable is done only by initializing it.
Declaration of an external variable is done by adding a keyword ‘extern” before the variable name.
extern data_type variable_name;
Note : The extern keyword before the variable only tells the compiler about the name and data type of variable without allocating any storage for it.
However, if you initialize that variable, then it also allocates storage for the extern variable.