Storage Class:: Types of Storage Classes
Storage Class:: Types of Storage Classes
'Storage' refers to the scope of a variable and memory allocated by compiler to store that variable. Scope of a variable is the boundary within which a variable can be used. Storage class defines the the scope and lifetime of a variable. From the point view of C compiler, a variable name identifies physical location from a computer where variable is stored. There are two memory locations in a computer system where variables are stored as : Memory and CPU Registers. Functions of storage class : To detemine the location of a variable where it is stored ? Set initial value of a variable or if not specified then setting it to default value. Defining scope of a variable. To determine the life of a variable.
Automatic Storage Class Register Storage Class Static Storage Class External Storage Class
Example :
auto int a;
void main() { auto int i=10; { auto int i=20; printf("\n\t %d",i); } printf("\n\n\t %d",i); }
Example :
register int a;
When the calculations are done in CPU, then the value of variables are transferred from main memory to CPU. Calculations are done and the final result is sent back to main memory. This leads to slowing down of processes. Register variables occur in CPU and value of that register variable is stored in a register within that CPU. Thus, it increases the resultant speed of operations. There is no waste of time, getting variables from memory and sending it to back again. It is not applicable for arrays, structures or pointers. It cannot not used with static or external storage class. Unary and address of (&) cannot be used with these variables as explicitly or implicitly.
#include <stdio.h> void main() { register int i=10; { register int i=20; printf("\n\t %d",i); } printf("\n\n\t %d",i); }
Keyword : static Storage Location : Main memory Initial Value : Zero and can be initialize once only. Life : depends on function calls and the whole application or program. Scope : Local to the block.
There are two types of static variables as : a) Local Static Variable b) Global Static Variable Static storage class can be used only if we want the value of a variable to persist between different function calls.
#include <stdio.h> void main() { int i; for (i=0; i<3; i++) incre(); }
svar++; printf("\n\n Automatic variable value : %d",avar); printf("\t Static variable value : %d",svar); }
Output :
Example :
extern int a;
The variable access time is very fast as compared to other storage classes. But few registers are available for user programs.
The variables of this class can be referred to as 'global or external variables.' They are declared outside the functions and can be invoked at anywhere in a program.