A storage class defines the visibility and the scope of a variable or a function in a program. It also defines the memory location and initial value of a variable.
There are four storage classes in C:
- Auto
- Register
- Static
- Extern
Let us discuss them one by one.
The “auto” Storage Class:
The auto storage class is the default storage class for all the local variables initialised in a C programming language. The auto storage class is initialized with an auto keyword. The scope of automatic variables are limited to the block they are defined. The memory assigned to the automatic variables gets freed once it exits the block.
Syntax:
int a; //here the variable is by default initialized as auto
auto int b;
Example:
#include <stdio.h> int main() { auto int a; auto float c; printf("%d %f",a,c); return 0; }
Here the program shows the values of the initialized auto variables which tends to be a garbage value, as the auto storage class gets initialized by default with a garbage value.
Output:
The “register” storage class:
The register storage class is used to store the variables in the CPU registers instead of RAM. They are stored in registers for faster accessibility. They are initialzed with the register keyword and with a default value of 0.
Syntax:
register int a;
Example Of “register” storage class:
#include <stdio.h> int main() { register int a; printf("%d",a); return 0; }
Here in the program the variable a is initialized with the register keyword and shows the default value initialized as 0.
Output:
The “static” storage class:
The variables once declared as static hold their value till the execution of the block where they are declared. Variables are by default initialized by a value of 0 or null. They are visible only to the block or function where they are declared. The variables are declared static using the static keyword.
Syntax Of “static” storage class:
static int a;
Example:
#include<stdio.h> static char c; static int i; static float f; static char s[100]; void main () { printf("%d %d %f %s",c,i,f); return 0; }
Here the program shows the initialized value of the static variables which results in values of 0 or null.
Output:
The “external” storage class:
The external storage class is defined with an external reference of the variable elsewhere in the program. The external storage class variables are declared with the extern keyword with default initial value as 0 or null.
Syntax Of “external” storage class:
//file1.h
int a;
extern int a;
Example of “external” storage class:
#include <stdio.h> int a; int main() { extern int a; printf("%d",a); }
Here in the program the variable is initialized with extern keyword with a linkage elsewhere in the program. The variable is initialized as a global variable and is declared in the main function for its use.
Output:
Hence we come to the end of the discussion on storage class in C, hope we have cleared all your doubts. Stay tuned for the next article on C language.