Storage Classes in C: auto, extern, static, register with Example
What is a Storage Class?
A storage class represents the visibility and a location of a variable. It tells from what 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?
Thus a storage class is used to represent the information about a variable.
NOTE: A variable is not only associated with a data type, its value but also a storage class.
There are total four types of standard storage classes. The table below represents the storage classes in 'C'.
Storage class | Purpose |
auto | It is a default storage class. |
extern | It is a global variable. |
static | It is a local variable which is capable of returning a value even when control is transferred to the function call. |
register | It is a variable which is stored inside a Register. |
Auto storage class
The variables defined using auto storage class are called as local variables. Auto stands for automatic storage class. A variable is in auto storage class by default if it is not explicitly specified.
The scope of an auto variable is limited with the particular block only. Once the control goes out of the block, the access is destroyed. This means only the block in which the auto variable is declared can access it.
A keyword auto is used to define an auto storage class. By default, an auto variable contains a garbage value.
Example, auto int age;
The program below defines a function with has two local variables
int add(void) { int a=13; auto int b=48; return a+b;}
We take another program which shows the scope level "visibility level" for auto variables in each block code which are independently to each other:
#include <stdio.h> int main( ) { auto int j = 1; { auto int j= 2; { auto int j = 3; printf ( " %d ", j); } printf ( "\t %d ",j); } printf( "%d\n", j);}
OUTPUT:
3 2 1
Extern storage class
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.
Keyword extern is used to declaring a global variable or function in another file to provide the reference of variable or function which have been already defined in the original file.
The variables defined using an extern keyword are called as global variables. These variables are accessible throughout the program. Notice that the extern variable cannot be initialized it has already been defined in the original file
Example, extern void display();
First File: main.c
#include <stdio.h> extern i; main() { printf("value of the external integer is = %d\n", i); return 0;}
Second File: original.c
#include <stdio.h> i=48;
Result:
value of the external integer is = 48
PROGRAMER BABU
Comments
Post a Comment