Storage classes specify the scope, lifetime and binding of variables.
To fully define a variable, one needs to mention not only its ‘type’ but also its storage class.
A variable name identifies some physical location within computer memory, where a collection of bits are allocated for storing values of variable.
Storage class tells us the following factors −
- Where the variable is stored (in memory or cpu register)?
- What will be the initial value of variable, if nothing is initialized?
- What is the scope of variable (where it can be accessed)?
- What is the life of a variable?
Lifetime
The lifetime of a variable defines the duration for which the computer allocates memory for it (the duration between allocation and deallocation of memory).
In C language, a variable can have automatic, static or dynamic lifetime.
- Automatic − A variable with automatic lifetime are created. Every time, their declaration is encountered and destroyed. Also, their blocks are exited.
- Static − A variable is created when the declaration is executed for the first time. It is destroyed when the execution stops/terminates.
- Dynamic − The variables memory is allocated and deallocated through memory management functions.
Storage Classes
There are four storage classes in C language −
Storage Class | Storage Area | Default initial value | Lifetime | Scope | Keyword |
---|---|---|---|---|---|
Automatic | Memory | Till control remains in block | Till control remains in block | Local | Auto |
Register | CPU register | Garbage value | Till control remains in block | Local | Register |
Static | Memory | Zero | Value in between function calls | Local | Static |
External | Memory | Garbage value | Throughout program execution | Global | Extern |
Example
Following is the C program for automatic storage class −
#include<stdio.h> main ( ){ auto int i=1;{ auto int i=2;{ auto int i=3; printf ("%d",i) } printf("%d", i); } printf("%d", i); }
Output
When the above program is executed, it produces the following output −
3 2 1
Example
Following is the C program for external storage class −
#include<stdio.h> extern int i =1; /* this ‘i’ is available throughout program */ main ( ){ int i = 3; /* this ‘i' available only in main */ printf ("%d", i); fun ( ); } fun ( ) { printf ("%d", i); }
Output
When the above program is executed, it produces the following output −
3 1