C Storage
Classes
Storage Classes in C are associated with variables for describing the features of any variable or functions in the C program. The storage classes define the scope, lifetime of the variable, visibility which helps the programmer to define a particular variable during the program’s runtime. The storage classes are preceded by data type.
The following are the four storage classes in C:
auto
Storage Class
The auto storage class in C comes by default when declaring a local variable. The keyword auto can also be used explicitly as its storage class.
Syntax:
int value; //contains auto by default
which is the same as
auto int value; //auto keyword used explicitly
The above variable name value with or without, can only be implemented with the local variables.
Register
Storage Class
The register storage class is implemented for local
variables whose value is stored in the place of RAM (Random Access Memory).
This is basically implemented when you want your variable the maximum size
equivalent to the size of the register. This uses the keyword register.
Syntax
register int counter;
Register variables are used while implementing loops in counter variables to make the program execution faster. Register variables work faster than variables stored in RAM which is a primary memory.
Example
for(register int counter=0; counter <=15; counter++)
{
// body
}
static
Storage Class
The static variables are popular in C programs which preserve the value of a variable even when the scope limit exceeds. Static storage class has its scope local to the function in which it is defined. In other hand, the global static variables can be accessed from any part of the program. The default value assigned is ‘0’ to the static variable by the compiler. The keyword ‘static’ is used to define this storage class in C.
Example
static int value = 10;
extern Storage class
The extern storage class in C is used to feature a variable to be used within different blocks of the same program. The extern variable can be overwritten in other block or function or within the block as well. Hence, the extern variable is same as the global variable which is assigned which is assigned with a value that can be accessed and used within the entire program. In other words, global variable can be made extern explicitly by implementing the keyword ‘extern’ preceded the variable name.
Example Program 1
#include
extern int val=10; // now the variable val can be accessed and used from anywhere
// main program
void main()
{
printf("Value is: %d\n", val);
}
Output
Value is: 10
The extern variable can be overridden with the local variable which is defined within the block or function.
Example Program 2
#include
extern int val=10; // now the variable val can be accessed and used from anywhere
// main program
void main()
{
val = 20; //the variable val is overridden with the value 20
printf("Value is: %d\n", val);
}
Output
Value is: 20