Page Stats
Visitor: 498
C - Storage classes
To define a variable we need to mention not only its data type but also its storage class. Storage classes will tells the compiler, where the variable is stored and what will be its default value. In C, different types of storage classes and different type of variable declaration are:
1. Auto variable
2. Register variable
3. Static variable
4. External variable
- Auto variable The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable. However you can use auto keyword to declare automatic variable.
- Register variable The register storage class is used to define local variables to be stored in a register instead of RAM.
- Static variable The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program. Therefore, making local variables static allows to maintain their values between function calls. It retains value between multiple functions call.
- External variable It is also known as global variable and it is visible in ALL the functions. Global variable is declared outside the function or scope block. Value change in any function will reflect in other functions. Extern keyword is use to declare external variable.
void main() { int x=10; //local variable also automatic auto int y=20; //local variable also automatic }
for(i=1;i<=10;i++) { static int a=10; a++; printf("%d ",a); }
11 12 13 14 15 16 17 18 19 20
if we do not apply static keyword then the output will be:
11 11 11 11 11 11 11 11 11 11
if we do not apply static keyword then the output will be:
11 11 11 11 11 11 11 11 11 11
int value1=20;//global variable extern int value2=20;//global variable void function() { printf("%d\n",value1); // 20 printf("%d\n",value2); // 20 }
Use register storage class very often because there are very few CPU registers and many of them might be busy. Also, we can't get the address of register variable.