C Storage class
In C language, storage classes are categories on basis of permanance of variable and scope of the variable within the program. There are four types of storage classes.
- Automatic variables
- External variables
- Static variables
- Register variables
1. Automatic variables
Automatic variables is always local to a function. Automatic variables always declared within a function. Scope of of automatic variable is restricted to a function only where it is declared. Automatic variables does not retain its value. All variable declared within a function is act as local variable of this function.
Advantages of using auto variables
Auto keyword is used to specify automatic variable but it is not necessary. See example below.
- int gt_add(); /* Function prototype */
- int main()
- /* value is automatic variable to function main() */
- int value = 0;
- /* Add function call with no argument */
- value = gt_add();
- printf(“value = %d\n”,value);
- return 0;
- int gt_add() /* Function definition */
- /* num1 , num2 and sum is automatic variable to function gt_add */
- int num1 = 0;
- int num2 = 0;
- int sum = 0;
- sum = num1 + num2;
- printf(“num1 = %d\n”,num1);
- printf(“num2 = %d\n”,num2);
- printf(“sum = %d\n”,sum);
- return sum;
2. External variables
External variable is a global variable. It is a variable defined outside of any function block. External variable is not associated with a single function. It is possible to define variables that are external to all functions, that is, variables that can be accessed by same name by any function. If we change value in one function will reflect in another function. External variable declaration must begin with ‘extern” keyword. Scope of external variable is through out the program.
Before using the external variable, i would like to explain difference between definition and declaration of external variables.
|Definition of external varaibles
Declaration of external varaibles
Advantages of using external variables
3. Static variables
Static variables is like automatic varisble but it must begin with “static” keyword and retain thgeir values throught out the life of program.
Advantages of using static variables
4. Register variables
Also register variables is like automatic variables but it must begin with “register” keyword. Values of register variables are stored in CPU registers. Scope of the register variables is within a function only.