Preview
Storage class in C
Storage class specifies the scope of a variable in a program. It demonstrates whether variable gets stored in RAM or registers. There are four types of storage classes in C language.
- auto
- register
- static
- extern
1. auto
They are also called automatic, local or internal variables. This storage class specifies automatic variables which are declared inside RAM. These variables get created when a function is invoked and removed when program control leaves the the function.
We don’t need to specify this storage class because variables are by default automatic. Keyword auto can also be used to specify that a variable is automatic.
Example: int a; or auto int a;
Program |
#include<stdio.h> int main() { auto int i=10; /*or int i;*/ printf(“\ni=%d”,i); return(0); } |
Output |
i=10 |
2. register
We use register keyword to declare register variables which get stored in computer’s registers in place of RAM. These variables are accessed faster than automatic variables.
Those variables should be declared register type which need to be used again and again like looping variables.
Example: register int a;
Program |
#include<stdio.h> int main() { register int i=10; printf(“\ni=%d”,i); return(0); } |
Output |
i=10 |
3. static
We declare static variables by using static keyword. They keep their values throughout the program execution till end. They get initialized once. They are of two types
i. Internal : The lifetime of these static variables is within the function where they are defined.
ii. External static variable: They are defined outside functions and are available to all functions of a program .
Program |
#include<stdio.h> void show() { static int i=10; i++; printf(“\ni=%d”,i); } int main() { show(); show(); show(); return(0); } |
Output |
i=10 i=11 i=12 |
Description |
In the above program, when the function show () is called for the first time, static variable i is initialized with value 10. When this function is called again, variable i will not be initialized again with 10 but it will take its previous value and increment it further with one with each call to function show (). |
4. extern
They are also called external variables or global variables.. We can use the extern keyword to declare external variables. They keep their values till the end of program execution. External variables can be accessed across multiple files.
Program |
#include<stdio.h> void demo(); int main() { extern int i; printf(“\ni=%d”,i); demo(); return(0); } int i=10; void demo() { i++; printf(“\ni=%d”,i); } |
Output |
i=10 i=11 |
Description |
Variable i has been defined after main () function, it can’t be directly used within the main() function so it has been made available within main() function by redeclaring the variable i within main() by using the keyword extern. |
Best Books of Computer Science